Java Reference
In-Depth Information
If you receive a java.net.BindException when you start the server, the server port
is currently in use. You need to terminate the process that is using the server port and then
restart the server.
Note
When you create a server socket, you have to specify a port (e.g., 8000) for the socket.
When a client connects to the server (line 67 in Client.java), a socket is created on the
client. This socket has its own local port. This port number (e.g., 2047) is automatically
chosen by the JVM, as shown in Figure 31.6.
client socket port
port number
Server
0
0
1
.
.
.
2047
Client
1
.
.
.
socket
socket
8000
.
.
.
.
.
.
F IGURE 31.6
The JVM automatically chooses an available port to create a socket for the
client.
To see the local port on the client, insert the following statement in line 70 in
Client.java.
System.out.println( "local port: " + socket.getLocalPort());
31.1 How do you create a server socket? What port numbers can be used? What happens
if a requested port number is already in use? Can a port connect to multiple clients?
Check
Point
31.2
What are the differences between a server socket and a client socket?
31.3
How does a client program initiate a connection?
31.4
How does a server accept a connection?
31.5
How are data transferred between a client and a server?
31.3 The InetAddress Class
The server program can use the InetAddress class to obtain the information about
the IP address and host name for the client.
Key
Point
Occasionally, you would like to know who is connecting to the server. You can use the
InetAddress class to find the client's host name and IP address. The InetAddress class
models an IP address. You can use the following statement in the server program to get an
instance of InetAddress on a socket that connects to the client.
InetAddress inetAddress = socket.getInetAddress();
Next, you can display the client's host name and IP address, as follows:
System.out.println( "Client's host name is " +
inetAddress.getHostName());
 
 
 
Search WWH ::




Custom Search