Returning a Response


Socket clientSock = serverSocket.accept(); DataOutputStream out =   new DataOutputStream(          clientSock.getOutputStream()); out.writeInt(someValue); out.close();



This phrase shows an example of how to return a response from a server to a client. The accept() method of the ServerSocket instance will return a Socket instance when a connection is made with a client. We then get the socket's output stream by calling the getOutputStream() method of the socket. We use the output stream to instantiate a DataOutputStream, which we then call the writeInt() method on to write an integer value, sending binary data to the client. Finally, we close the socket using the close() method of the Socket.

In this phrase, we use the write() method, but the DataOutputStream has many other methods available to write data from any primitive Java data type. The available methods for writing binary data include: write(), writeBoolean(), writeByte(), writeBytes(), writeChar(), writeChars(), writeDouble(), writeFloat(), writeInt(), writeLong(), and writeShort(). See the JavaDoc for details on using these methods and other methods of the DataOutputStream class:http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.html

If we wanted to write text data to the client, we could use the following code:

Socket clientSock = serverSocket.accept(); PrintWriter out =    new PrintWriter(new OutputStreamWriter(           clientSock.getOutputStream()), true); out.println("Hello World"); out.close();


Instead of creating a DataOutputStream, here we create an OutputStreamWriter and a PrintWriter. We use the print() method of the PrintWriter to write a text string to the client. The second parameter that we pass to the PrintWriter constructor sets the auto-flush option. Setting this to true will cause the println(), printf(), and format() methods to automatically flush the output buffer. In our phrase, we use the println() method; thus, it is not necessary to explicitly call the flush() method. As always, when we are done using the PrintWriter, we call the close() method to close the stream.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net