Java Reference
In-Depth Information
19
20
for (;;) { // Run forever, accepting and servicing connections
21
Socket clntSock = servSock.accept();
// Get client connection
22
23
System.out.println("Handling client at " +
24
clntSock.getInetAddress().getHostAddress()+"onport " +
25
clntSock.getPort());
26
27
InputStream in = clntSock.getInputStream();
28
OutputStream out = clntSock.getOutputStream();
29
30
// Receive until client closes connection, indicated by −1 return
31
while ((recvMsgSize = in.read(byteBuffer)) != −1)
32
out.write(byteBuffer, 0, recvMsgSize);
33
34
clntSock.close(); // Close the socket. We are done with this client!
35
}
36
/* NOT REACHED */
37
}
38
}
TCPEchoServer.java
1.
Application setup and parameter parsing:
lines 0-12
2.
Server socket creation:
line 15
servSock
listens for client connection requests on the port specified in the constructor.
3.
Loop forever, iteratively handling incoming connections:
lines 20-35
Accept an incoming connection:
line 21
The sole purpose of a
ServerSocket
instance is to supply a new, connected
Socket
instance for each new TCP connection. When the server is ready to handle a client, it
calls
accept()
, which blocks until an incoming connection is made to the
ServerSocket
's
port.
accept()
then returns an instance of
Socket
that is already
connected
to the
remote socket and ready for reading and writing.
Report connected client:
lines 23-25
We can query the newly created
Socket
instance for the address and port of the
connecting client. The
getInetAddress()
method of
Socket
returns an instance of
InetAddress
containing the address of the client. We call
getHostAddress()
to return
the IP address as a dotted-quad
String
. The
getPort()
method of
Socket
returns the
port of the client.
Get socket input and output streams:
lines 27-28
Bytes written to this socket's
OutputStream
will be read from the client's socket's
InputStream
, and bytes written to the client's
OutputStream
will be read from this
socket's
InputStream
.
Search WWH ::
Custom Search