Returning a Response (String or Binary)


You need to write a string or binary data to the client.


The socket gives you an InputStream and an OutputStream. Use them.


The client socket examples in the previous chapter called the getInputStream( ) and getOutputStream( ) methods. These examples do the same. The main difference is that they get the socket from a ServerSocket’s accept( ) method, and that normally the server creates or modifies the data and writes it to the client. Example 16-3 is a simple Echo server, which the Echo client of Section 15.5 can connect to. This server handles one complete connection with a client, then goes back and does the accept( ) to wait for the next client.

Example 16-3.

/** * EchoServer - create server socket, do I-O on it. */ public class EchoServer { /** Our server-side rendezvous socket */ protected ServerSocket sock; /** The port number to use by default */ public final static int ECHOPORT = 7; /** Flag to control debugging */ protected boolean debug = true; /** main: construct and run */ public static void main(String[] argv) { new EchoServer(ECHOPORT).handle( ); } /** Construct an EchoServer on the given port number */ public EchoServer(int port) { try { sock = new ServerSocket(port); } catch (IOException e) { System.err.println("I/O error in setup"); System.err.println(e); System.exit(1); } } /** This handles the connections */ protected void handle( ) { Socket ios = null; BufferedReader is = null; ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.