Returning a Response (String or Binary)

Problem

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

Solution

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

Discussion

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.java

/** * 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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.