Java Reference
In-Depth Information
Example 8-4 is line oriented. It reads a line of input from the console, sends it to the
server, and waits to read a line of output it gets back.
Half-closed sockets
The close() method shuts down both input and output from the socket. On occasion,
you may want to shut down only half of the connection, either input or output. The
shutdownInput() and shutdownOutput() methods close only half the connection:
public void shutdownInput () throws IOException
public void shutdownOutput () throws IOException
Neither actually closes the socket. Instead, they adjust the stream connected to the socket
so that it thinks it's at the end of the stream. Further reads from the input stream after
shutting down input return -1. Further writes to the socket after shutting down output
throw an IOException .
Many protocols, such as finger, whois, and HTTP, begin with the client sending a request
to the server, then reading the response. It would be possible to shut down the output
after the client has sent the request. For example, this code fragment sends a request to
an HTTP server and then shuts down the output, because it won't need to write anything
else over this socket:
try ( Socket connection = new Socket ( "www.oreilly.com" , 80 )) {
Writer out = new OutputStreamWriter (
connection . getOutputStream (), "8859_1" );
out . write ( "GET / HTTP 1.0\r\n\r\n" );
out . flush ();
connection . shutdownOutput ();
// read the response...
} catch ( IOException ex ) {
ex . printStackTrace ();
}
Notice that even though you shut down half or even both halves of a connection, you
still need to close the socket when you're through with it. The shutdown methods simply
affect the socket's streams. They don't release the resources associated with the socket,
such as the port it occupies.
The isInputShutdown() and isOutputShutdown() methods tell you whether the input
and output streams are open or closed, respectively. You can use these (rather than
isConnected() and isClosed() ) to more specifically ascertain whether you can read
from or write to a socket:
public boolean isInputShutdown ()
public boolean isOutputShutdown ()
Search WWH ::




Custom Search