Java Reference
In-Depth Information
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
these ones get the socket from a ServerSocket 's accept() method. Another distinction is,
by definition, that normally the server creates or modifies the data and sends it to the client.
Example 16-3 is a simple Echo server, which the Echo client of Reading and Writing Textual
Data 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
public
public class
EchoServer {
/** Our server-side rendezvous socket */
protected
class EchoServer
protected ServerSocket sock ;
/** The port number to use by default */
public
public final
int ECHOPORT = 7 ;
/** Flag to control debugging */
protected
final static
static int
protected boolean
boolean debug = true
true ;
/** main: construct and run */
public
public static
static void
void main ( String [] args ) {
int
int p = ECHOPORT ;
iif ( args . length == 1 ) {
try
try {
p = Integer . parseInt ( args [ 0 ]);
} catch
catch ( NumberFormatException e ) {
System . err . println ( "Usage: EchoServer [port#]" );
System . exit ( 1 );
}
}
new
new EchoServer ( p ). handle ();
}
/** Construct an EchoServer on the given port number */
public
public EchoServer ( int
int port ) {
try
try {
sock = new
new ServerSocket ( port );
} catch
catch ( IOException e ) {
System . err . println ( "I/O error in setup" );
Search WWH ::




Custom Search