Java Reference
In-Depth Information
up byteBuffer until we receive as many bytes as we sent. If the TCP connection is closed by
the other end, read() returns
1. For the client, this indicates that the server prematurely
closed the socket.
Why not just a single read? TCP does not preserve read() and write() message
boundaries. That is, even though we sent the echo string with a single write() , the echo
server may receive it in multiple chunks. Even if the echo string is handled in one chunk
by the echo server, the reply may still be broken into pieces by TCP. One of the most
common errors for beginners is the assumption that data sent by a single write() will
always be received in a single read() .
6. Print echoed string: line 35
To print the server's response, we must convert the byte array to a string using the default
character encoding.
7. Close socket: line 37
When the client has finished receiving all of the echoed data, it closes the socket.
We can communicate with an echo server named server.example.com with IP address
169.1.1.1 in either of the following ways:
% java TCPEchoClient server.example.com "Echo this!"
Received: Echo this!
% java TCPEchoClient 169.1.1.1 "Echo this!"
Received: Echo this!
See TCPEchoClientGUI.java on the topic's Web site for an implementation of the TCP echo client
with a graphical interface.
Socket
Constructors
Socket ( InetAddress remoteAddr , int remotePort )
Socket ( String remoteHost , int remotePort )
Socket ( InetAddress remoteAddr , int remotePort , InetAddress localAddr , int localPort )
Socket ( String remoteHost , int remotePort , InetAddress localAddr , int localPort )
Constructs a TCP socket connected to the specified remote address and port. The first
two forms of the constructor do not specify the local address and port, so a default
local address and some available port are chosen. Specifying the local address may be
useful on a host with multiple interfaces.
remoteAddr
Remote host address
remoteHost
Remote host name or IP address (in dotted-quad form)
remotePort
Remote port
 
Search WWH ::




Custom Search