Java Reference
In-Depth Information
4. Close the connection.
This is exactly the same as for the server process (using method close of class
Socket ).
The code below shows the client program for our example. In addition to an
input stream to accept messages from the server, our client program will need to set
up an input stream (as another Scanner object) to accept user messages from the
keyboard. As for the server, the lines of code corresponding to each of the above
steps have been clearly marked with emboldened comments.
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoClient
{
private static InetAddress host;
private static fi nal int PORT = 1234;
public static void main(String[] args)
{
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer()
{
Socket link = null; //Step 1.
try
{
link = new Socket(host,PORT); //Step 1.
Scanner input =
new Scanner(link.getInputStream());
//Step 2.
PrintWriter output =
new PrintWriter(
link.getOutputStream(),true); //Step 2.
//Set up stream for keyboard entry…
Scanner userEntry = new Scanner(System.in);
Search WWH ::




Custom Search