Java Reference
In-Depth Information
Writing to Servers with Sockets
In the examples so far, the server has only written to client sockets. It hasn't read from
them. Most protocols, however, require the server to do both. This isn't hard. You'll
accept a connection as before, but this time ask for both an InputStream and an Out
putStream . Read from the client using the InputStream and write to it using the Out
putStream . The main trick is understanding the protocol: when to write and when to
read.
The echo protocol, defined in RFC 862, is one of the simplest interactive TCP services.
The client opens a socket to port 7 on the echo server and sends data. The server sends
the data back. This continues until the client closes the connection. The echo protocol
is useful for testing the network to make sure that data is not mangled by a misbehaving
router or firewall. You can test echo with Telnet like this:
$ telnet rama . poly . edu 7
Trying 128.238 . 10.212 ...
Connected to rama . poly . edu .
Escape character is ' ^] ' .
This is a test
This is a test
This is another test
This is another test
9876543210
9876543210
^]
telnet > close
Connection closed .
This sample is line oriented because that's how Telnet works. It reads a line of input from
the console, sends it to the server, then waits to read a line of output it gets back. However,
the echo protocol doesn't require this. It echoes each byte as it receives it. It doesn't really
care whether those bytes represent characters in some encoding or are divided into lines.
Unlike many protocols, echo does not specify lockstep behavior where the client sends
a request but then waits for the full server response before sending any more data.
Unlike daytime and time, in the echo protocol the client is responsible for closing the
connection. This makes it even more important to support asynchronous operation
with many threads because a single client can remain connected indefinitely. In
Example 9-5 , the server spawns up to 500 threads.
Example 9-5. An echo server
import java.nio.* ;
import java.nio.channels.* ;
import java.net.* ;
import java.util.* ;
import java.io.IOException ;
Search WWH ::




Custom Search