Java Reference
In-Depth Information
After the socket is open, you can use input and output streams to read and write from
that socket:
BufferedInputStream bis = new
BufferedInputStream(connection.getInputStream());
DataInputStream in = new DataInputStream(bis);
BufferedOutputStream bos = new
BufferedOutputStream(connection.getOutputStream());
DataOutputStream out= new DataOutputStream(bos);
You don't need names for all these objects; they are used only to create a stream or
stream reader. For an efficient shortcut, combine several statements as in this example
using a Socket object named sock :
DataInputStream in = new DataInputStream(
new BufferedInputStream(
sock.getInputStream()));
In this statement, the call to sock.getInputStream() returns an input stream associated
with that socket. This stream is used to create a BufferedInputStream , and the buffered
input stream is used to create a DataInputStream .
The only variables you are left with are sock and in , the two objects needed as you
receive data from the connection and close it afterward. The intermediate objects—a
BufferedInputStream and an InputStream —are needed only once.
After you're finished with a socket, don't forget to close it by calling the close()
method. This also closes all the input and output streams you might have set up for that
socket. For example:
connection.close();
Socket programming can be used for many services delivered using TCP/IP networking,
including telnet, Simple Mail Transfer Protocol (SMTP) for incoming mail, Network
News Transfer Protocol (NNTP) for Usenet news, and finger.
The last of these, finger, is a protocol for asking a system about one of its users. By set-
ting up a finger server, a system administrator enables an Internet-connected machine to
answer requests for user information. Users can provide information about themselves by
creating .plan files, which are sent to anyone who uses finger to find out more about
them.
Although it has fallen into disuse in recent years because of security concerns, finger was
the most popular way that Internet users published facts about themselves and their activ-
Search WWH ::




Custom Search