Java Reference
In-Depth Information
32
totalBytesRcvd += bytesRcvd;
33
}
34
35
System.out.println("Received: " + new String(byteBuffer));
36
37
socket.close(); // Close the socket and its streams
38
}
39 }
TCPEchoClient.java
1. Application setup and parameter parsing: lines 0-14
Convert the echo string: line 12
TCP sockets send and receive sequences of bytes. The getBytes() method of String
returns a byte array representation of the string. (See Section 3.1 for a discussion of
character encodings.)
Determine the port of the echo server: line 14
The default echo port is 7. If we specify a third parameter, Integer.parseInt() takes
the string and returns the equivalent integer value.
2. TCP socket creation: line 17
The Socket constructor creates a socket and establishes a connection to the specified
server, identified either by name or IP address. Note that the underlying TCP deals only
with IP addresses. If a name is given, the implementation resolves it to the correspond-
ing address. If the connection attempt fails for any reason, the constructor throws an
IOException .
3. Get socket input and output streams: lines 20-21
Associated with each connected Socket instance is an InputStream and OutputStream .We
send data over the socket by writing bytes to the OutputStream just as we would any other
stream, and we receive by reading from the InputStream .
4. Send the string to echo server: line 23
The write() method of OutputStream transmits the given byte array over the connection
to the server.
5. Receive the reply from the echo server: lines 25-33
Since we know the number of bytes to expect from the echo server, we can repeatedly
receive bytes until we have received the same number of bytes we sent. This particular
form of read() takes three parameters: 1) buffer to receive into, 2) byte offset into the
buffer where the first byte received should be placed, and 3) the maximum number of
bytes to be placed in the buffer. read() blocks until some data is available, reads up
to the specified maximum number of bytes, and returns the number of bytes actually
placed in the buffer (which may be less than the given maximum). The loop simply fills
Search WWH ::




Custom Search