Java Reference
In-Depth Information
Server Host
Step 1: Create a server socket on a port, e.g.,
8000, using the following statement:
Client Host
Step 3: A client program uses the following
statement to connect to the server:
Network
ServerSocket serverSocket = new
ServerSocket(8000);
Socket socket = new
Socket(serverHost, 8000);
Step 2: Create a socket to connect to a client,
using the following statement:
Socket socket =
serverSocket.accept();
I/O Stream
F IGURE 31.1
The server creates a server socket and, once a connection to a client is established, connects to the client
with a client socket.
For instance, the email server runs on port 25, and the Web server usually runs on port 80.
You can choose any port number that is not currently used by other programs. The following
statement creates a server socket serverSocket :
ServerSocket serverSocket = new ServerSocket(port);
Note
Attempting to create a server socket on a port already in use would cause a
java.net.BindException .
BindException
31.2.2 Client Sockets
After a server socket is created, the server can use the following statement to listen for
connections:
Socket socket = serverSocket.accept();
This statement waits until a client connects to the server socket. The client issues the follow-
ing statement to request a connection to a server:
connect to client
Socket socket = new Socket( serverName, port );
This statement opens a socket so that the client program can communicate with the server.
serverName is the server's Internet host name or IP address. The following statement creates
a socket on the client machine to connect to the host 130.254.204.33 at port 8000:
client socket
use IP address
Socket socket = new Socket( "130.254.204.33" , 8000 )
Alternatively, you can use the domain name to create a socket, as follows:
use domain name
Socket socket = new Socket( "liang.armstrong.edu" , 8000 );
When you create a socket with a host name, the JVM asks the DNS to translate the host name
into the IP address.
Note
A program can use the host name localhost or the IP address 127.0.0.1 to refer
to the machine on which a client is running.
localhost
 
 
Search WWH ::




Custom Search