Thursday, April 21, 2011

Tutorial Synchronous Socket Programming using JAVA (For Client)

A client application opens a connection to a server by constructing a Socket that specifies the hostname and port number of the desired server:

try {
Socket sock = new Socket("wupost.wustl.edu", 25);
} catch ( UnknownHostException e ) {
System.out.println("Can't find host.");
} catch ( IOException e ) {
System.out.println("Error connecting to host.");
}





This code fragment attempts to connect a Socket to port 25 (the SMTP mail service) of the host wupost.wustl.edu. The client handles the possibility that the hostname can't be resolved (UnknownHostException) and that it might not be able to connect to it (IOException). The constructor can also accept a string containing the host's IP address:

Socket sock = new Socket("22.66.89.167", 25);

Once a connection is made, input and output streams can be retrieved with the Socket getInputStream( ) and getOutputStream( ) methods. The following (rather arbitrary) code sends and receives some data with the streams:

try {
Socket server = new Socket("foo.bar.com", 1234);
InputStream in = server.getInputStream( );
OutputStream out = server.getOutputStream( );

// write a byte
out.write(42);

// write a newline or carriage return delimited string
PrintWriter pout = new PrintWriter( out, true );
pout.println("Hello!");

// read a byte
byte back = (byte)in.read( );

// read a newline or carriage return delimited string
BufferedReader bin =
new BufferedReader( new InputStreamReader( in ) );
String response = bin.readLine( );

// send a serialized Java object
ObjectOutputStream oout = new
ObjectOutputStream( out );
oout.writeObject( new java.util.Date( ) );
oout.flush( );

server.close( );
}
catch (IOException e ) { ... }


In this exchange, the client first creates a Socket for communicating with the server. The Socket constructor specifies the server's hostname (foo.bar.com) and a prearranged port number (1234). Once the connection is established, the client writes a single byte to the server using the OutputStream's write( ) method. To send a string of text more easily, it then wraps a PrintWriter around the OutputStream. Next, it performs the complementary operations: reading a byte from the server using InputStream's read( ) method and then creating a BufferedReader from which to get a full string of text. Finally, we do something really funky and send a serialized Java object to the server, using an ObjectOutputStream.

No comments:

Post a Comment