Week 7: Java Client and Server Using Sockets

 

Overview

 

What is a Socket

 

Read and Write Using Java Socket (Client Side)

  1. Open a socket.
  2. Open an input stream and output stream to the socket.
  3. Read from and write to the stream according to the server's protocol.
  4. Close streams.
  5. Close sockets.

 

Client Programming in Java

try 
{
	echoSocket = new Socket("richard.rchland.ibm.com", 7);
	os = new DataOutputStream(echoSocket.getOutputStream());
	is = new DataInputStream(echoSocket.getInputStream());
} catch (UnknownHostException e) 
{
	System.err.println("Don't know about host: richard.rchland.ibm.com");
} catch (IOException e) 
{
	System.err.println("Couldn't get I/O for the connection to: richard.rchland.ibm.com");
}
	String userInput;
		
        while ((userInput = stdIn.readLine()) != null) 
	{
              os.writeBytes(userInput);
              os.writeByte('\n');
              System.out.println("echo: " + is.readLine());
        }  
 	//The readLine() method blocks until the server echos the information back
	os.close();
        is.close();
        echoSocket.close();

 

Server Programming in Java

ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(8888);
        } catch (IOException e) {
            System.out.println("Could not listen on port: " + 8888 + ", " + e);
            System.exit(1);
        }
Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("Accept failed: " + 8888 + ", " + e);
            System.exit(1);
        }
// Standard Java way of doing input and output 
BufferedReader is = new BufferedReader(new InputStreamReader( clientSocket.getInputStream() ));                                 
PrintWriter os = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream(), 1024), false);
            
String inputLine;

while ((inputLine = is.readLine()) != null) {
       // Echo the line out
       if (inputLine.equals("QUIT"))
           break;
       System.out.println("Input [" + inputLine + "] come in"); 
       os.println(inputLine);
       os.flush();
}

 

Lab

Create two Java applications EchoClient and EchoServer to build a mini client-server application that will enable the server to echo out whatever the client input

The EchoClient application should

The EchoServer application should

Note: The client and server programs should run in the same machine (host). The server program should be started first.

 

Copyright 1996-2001 OpenLoop Computing. All rights reserved.