FileDocCategorySizeDatePackage
EchoServer.javaAPI DocExample2043Sat Oct 26 09:53:50 BST 2002None

EchoServer

public class EchoServer extends Object
EchoServer - create server socket, do I-O on it.
author
Ian Darwin
version
Copyright (c) 1995, 1996, 1997, 2000 Ian F. Darwin

Fields Summary
protected ServerSocket
sock
Our server-side rendezvous socket
public static final int
ECHOPORT
The port number to use by default
protected boolean
debug
Flag to control debugging
Constructors Summary
public EchoServer(int port)
Construct an EchoServer on the given port number

		try {
			sock = new ServerSocket(port);
		} catch (IOException e) {
			System.err.println("I/O error in setup");
			System.err.println(e);
			System.exit(1);
		}
	
Methods Summary
protected voidhandle()
This handles the connections

		Socket ios = null;
		BufferedReader is = null;
		PrintWriter os = null;
		while (true) {
			try {
				System.out.println("Waiting for client...");
				ios = sock.accept();
				System.err.println("Accepted from " +
					ios.getInetAddress().getHostName());
				is = new BufferedReader(
					new InputStreamReader(ios.getInputStream(), "8859_1"));
				os = new PrintWriter(
						new OutputStreamWriter(
							ios.getOutputStream(), "8859_1"), true);
				String echoLine;
				while ((echoLine = is.readLine()) != null) {
					System.err.println("Read " + echoLine);
					os.print(echoLine + "\r\n");
					os.flush();
					System.err.println("Wrote " + echoLine);
				}
				System.err.println("All done!");
			} catch (IOException e) {
				System.err.println(e);
			} finally {
				try {
					if (is != null)
						is.close();
					if (os != null)
						os.close();
					if (ios != null)
						ios.close();
				} catch (IOException e) {
					// These are unlikely, but might indicate that
					// the other end shut down early, a disk filled up
					// but wasn't detected until close, etc.
					System.err.println("IO Error in close");
				}
			}
		}
		/*NOTREACHED*/
	
public static voidmain(java.lang.String[] argv)
main: construct and run


	     
	     
		new EchoServer(ECHOPORT).handle();