Java Reference
In-Depth Information
by issuing a break , which causes the loop to end. Control then returns to the main()
method.
out.println("Server received communication!");
while ((s = in.readLine()) != null) {
System.out.println("received from client: " + s);
out.flush();
break;
}
In a real-life server program, the server would most likely listen endlessly without
using a break to end communication. To handle multiple concurrent clients, each client
connection would spawn a separate Thread to handle communication. The server
would do something useful with the client communication as well. In the case of an
HTML server, it would send back an HTML message to the client. On an SMTP server,
the client would send an e-mail message to the server, and the server would then pro-
cess the e-mail and send it. Socket communication is used for just about any TCP
transmission, and both the client and servers create new sockets to perform a successful
communication.
21-2. Defining a Network Connection to a
Server
Problem
You need to establish a connection to a remote server.
Solution
Create a Socket connection to the remote server using its name and port number
where the server is listening for incoming client requests. The following example class
creates a Socket connection to a remote server. The code then sends a textual mes-
sage to the server and receives a response. In the example, the server that the client is
attempting to contact is named server-name and the port number is 1234 .
Search WWH ::




Custom Search