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; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access