Java Reference
In-Depth Information
In this example, the server will await ('listen for') a connection from a client on
port 1234.
2. Put the server into a waiting state.
The server waits indefi nitely ('blocks') for a client to connect. It does this by calling
method accept of class ServerSocket , which returns a Socket object when a connec-
tion is made. For example:
Socket link = serverSocket.accept();
3. Set up input and output streams .
Methods getInputStream and getOutputStream of class Socket are used to get ref-
erences to streams associated with the socket returned in step 2. These streams
will be used for communication with the client that has just made connection. For
a non-GUI application, we can wrap a Scanner object around the InputStream
object returned by method getInputStream , in order to obtain string-orientated
input (just as we would do with input from the standard input stream, System.in ).
For example:
Scanner input = new Scanner(link.getInputStream());
Similarly, we can wrap a PrintWriter object around the OutputStream object
returned by method getOutputStream . Supplying the PrintWriter constructor with a
second argument of true will cause the output buffer to be fl ushed for every call
of println (which is usually desirable). For example:
PrintWriter output =
new PrintWriter(link.getOutputStream(),true);
4. Send and receive data.
Having set up our Scanner and PrintWriter objects, sending and receiving data is
very straightforward. We simply use method nextLine for receiving data and method
println for sending data, just as we might do for console I/O. For example:
output.println("Awaiting data…");
String input = input.nextLine();
5. Close the connection (after completion of the dialogue).
This is achieved via method close of class Socket . For example:
link.close();
The following example program is used to illustrate the use of these steps.
Example
In this simple example, the server will accept messages from the client and will
keep count of those messages, echoing back each (numbered) message. The main
protocol for this service is that client and server must alternate between sending and
receiving (with the client initiating the process with its opening message, of course).
The only details that remain to be determined are the means of indicating when the
Search WWH ::




Custom Search