Java Reference
In-Depth Information
Receive and repeat data until the client closes: lines 30-32
The while loop repeatedly reads bytes (when available) from the input stream and
immediately writes the same bytes back to the output stream until the client closes
the connection. The read() method of InputStream reads up to the maximum number
of bytes the array can hold (in this case, BUFSIZE bytes) into the byte array ( byteBuffer )
and returns the number of bytes read. read() blocks until data is available and returns
1 if there is no data available, indicating that the client closed its socket. In the echo
protocol, the client closes the connection when it has received the number of bytes
back that it sent, so in the server we expect to receive a 1 from read() . Recall that in
the client, receiving a 1 from read() indicates an error because it indicates that the
server prematurely closed the connection.
As previously mentioned, read() does not have to fill the entire byte array to
return. In fact, it can return after having read only a single byte. The write() method
of OutputStream writes recvMsgSize bytes from byteBuffer to the socket. The second
parameter indicates the offset into the byte array of the first byte to send. In this case,
0 indicates to take bytes starting from the front of byteBuffer . If we had used the
form of write() that takes only the buffer argument, all the bytes in the buffer array
would have been transmitted, possibly including bytes that were not received from
the client!
Close client socket: line 34
ServerSocket
Constructors
ServerSocket ( int localPort )
ServerSocket ( int localPort , int queueLimit )
ServerSocket ( int localPort , int queueLimit , InetAddress localAddr )
Construct a TCP socket that is ready to accept incoming connections to the specified
local port. Optionally, the size of the connection queue and the local address can be
set.
localPort
Local port. A port of 0 allows the constructor to pick any
available port.
queueLimit
The maximum size of the queue of incomplete connections
and sockets waiting to be accept() ed. If a client connection
request arrives when the queue is full, the connection is
refused. Note that this may not necessarily be a hard limit.
For most platforms, it cannot be used to precisely control
client population.
 
Search WWH ::




Custom Search