Distributed System and Cloud Computing Lab Manual
ISBN 9788119221868

Highlights

Notes

  

Chapter 1: Remote Process Communication

Description:

Socket Programming refers to writing programs that execute across multiple computers in which the devices are all connected to each other using a network. A Server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. The client and server can communicate by writing to or reading from their socket.

A Socket is simply an endpoint for communication between machines.

There are two communication protocol that one can use for Socket Programming:

    1) Transmission control protocol (TCP)

    2) User Datagram Protocol (UDP)

Transmission Control Protocol.

TCP is a connection oriented protocol. In order to do communication over the TCP Protocol, a connection must be established between the pair of sockets. While on of the socket listen for connection request (Server), the other ask for connection (client). Once two socket have been connected, they can be used to transmit data in both direction.

Fig: Socket-based client and server programming.

Fig: Socket-based client and server programming.

Classes used for Socket programming:

    1) Socket

    Socket class represents the socket that both the client and the server use to communicate with each other.

    2) ServerSocket

    The ServerSocket class used by server application to obtain a port and listen for client requests.

Steps for creating a simple Server Program:

  • Step 1) Open the Server Socket.
    • ServerSocket ss=new ServerSocket(PORT);
  • Step 2) Wait for the client request.
    • Socket client=ss.accept();
  • Step 3) Create I/O Streams for the communicating to the client.
    • DataInputStream dis=new DataInputStream(client.getInputStream());
    • DataOutputStream dos=new DataOutputStream(client.getOutPutStream());
  • Step 4) Perform communication with the client.
    • Receive from client: => String str=dis.readUTF(); Send data to client: => dos.writeUTF(“Hello”);
  • Step 5) Close the socket.
    • Client.close();

Steps for creating a simple Client Program:

  • Step 1) Create a Socket Object.
    • Socket s=new Socket(server,port_id);
  • Step 2) Create I/O Streams for the communicating to the server.
    • DataInputStream dis=new
    • DataInputStream(client.getInputStream());
    • DataOutputStream dos=new DataOutputStream(client.getOutPutStream());
  • Step 3) Perform communication with the server.
    • Receive data from server: => String str=dis.readUTF(); Send data to the server: => dos.writeUTF(“Hello”);
  • Step 4) Close the socket.
    • s.close();

User Datagram Protocol.

UDP is a connection less protocol that allows for packets of data to be transmitted. Datagram Packets are used to implement a connection less packet delivery service supported by the UDP Protocol. Each message is transferred from source machine to destination based on information contained within that packet.

The format of Datagram Packet is:

The class DatagramPacket contain several constructors that can be used for creating packet object. For Example: DatagramPacket(byte[] buff, int length, InetAddress address, int port);

The class datagramSocket support various methods that can be used for transmitting or receiving data over the network, The two key methods are:

void send(DatagramPacket p) => send a datagram packet from this socket.

void receive(DatagramPacket p) => receive a datagram packet from this socket.

Program 1.1: Develop a program for one way client and server communication using java Socket, where client sends a message to the server, then the server reads the message and print it.

Source Code:

Filename: DemoClient.java

import java.net.*;

import java.io.*;

public class DemoClient

{

  • public static void main(String args[]) throws Exception
  • {
    • Socket s=new Socket(“localhost”,1234);
    • DataOutputStream dis=new DataOutputStream(s.getOutputStream()); dis.writeUTF(“Hello!! How are you”);
    • s.close();
  • }

}

Filename: DemoServer.java:

import java.net.*;

import java.io.*;

public class DemoServer

{

  • public static void main(String args[]) throws Exception
  • {
    • ServerSocket ss=new ServerSocket(1234); Socket s=ss.accept();
    • DataInputStream dis=new DataInputStream(s.getInputStream()); String msg=dis.readUTF();
    • System.out.println(“Message from client:” +msg);
  • }

}

OUTPUT:

DemoClient.java

DemoServer.java

Program 1.2 Develop a program for client server chat using java socket.

Source Code:

Filename: MyClient.java

import java.net.*;

import java.io.*;

import java.util.*;

public class My_Client

{

  • public static void main(String args[]) throws Exception
  • {
    • String str;
    • Socket s=new Socket(“localhost”,3333);
    • DataInputStream dis=new DataInputStream(s.getInputStream());
    • DataOutputStream dos=new DataOutputStream(s.getOutputStream()); Scanner in=new Scanner(System.in);
    • while(true)
    • {
      • System.out.print(“Client says:”); str=in.nextLine(); dos.writeUTF(str); str=dis.readUTF();
      • System.out.println(“Server says:” +str); if(str.equals(“exit”))
        • break;
      • }
      • s.close();
    • }

}

Filename: MyServer.java:

import java.net.*;

import java.io.*;

import java.util.*;

public class My_Server

{

  • public static void main(String args[]) throws Exception
  • {
    • String str;
    • ServerSocket ss=new ServerSocket(3333); Socket s=ss.accept();
    • DataInputStream dis=new DataInputStream(s.getInputStream());
    • DataOutputStream dos=new DataOutputStream(s.getOutputStream()); Scanner in=new Scanner(System.in);
    • while(true)
    • {
      • str=dis.readUTF(); if (str.equals(“exit”))
      • {
        • dos.writeUTF(“exit”);
      • break;
    • }
      • System.out.println(“ Client says:” +str); System.out.print(“Server says:”); str=in.nextLine();
      • dos.writeUTF(str);
    • }
    • ss.close();
    • s.close();
  • }

}

OUTPUT:

My_Client.java

My_Server.java

Program 1.3: Develop a program for one way client and server communication using Datagram Socket.

Filename: UDPClient.java

import java.net.*; import java.io.*;

public class UDPClient

{

  • public static void main(String args[]) throws Exception
  • {
    • String s=“How are you”;
    • DatagramSocket ds=new DatagramSocket();
    • InetAddress ip=InetAddress.getByName(“localhost”);
    • DatagramPacket p=new DatagramPacket(s.getBytes(),s.length(),ip,2222); ds.send(p);
  • }

}

Filename: UDPServer.java:

import java.net.*; import java.io.*;

public class UDPServer

{

  • public static void main(String args[]) throws Exception
  • {
    • DatagramSocket ds=new DatagramSocket(2222); byte[] b=new byte[1024];
    • DatagramPacket p=new DatagramPacket(b,1024); ds.receive(p);
    • String msg=new String(p.getData(),0,p.getLength()); System.out.println(“Message from client:” +msg);
  • }

}

OUTPUT:

UDPClient.java

UDPServer.java

Program 1.4: Implement a server to find whether an entered number is odd or even using Datagram Socket.

Source Code:

Filename: ClientUDP.java:

import java.net.*; import java.io.*; import java.util.*;

public class ClientUDP

{

  • public static void main(String args[]) throws Exception
  • {
    • Scanner in=new Scanner(System.in); System.out.println(“Enter a number”); String a=in.nextLine();
    • byte[] t1=a.getBytes();
    • InetAddress ip=InetAddress.getByName(“localhost”); DatagramPacket p=new DatagramPacket(t1,a.length(),ip,2222); DatagramSocket ds=new DatagramSocket();
    • ds.send(p);
  • }

}

Filename: ServerUDP.java:

import java.net.*; import java.io.*; import java.util.*;

public class ServerUDP

{

  • public static void main(String args[]) throws Exception
  • {
      • DatagramSocket ds=new DatagramSocket(2222); byte[] b=new byte[1024];
      • DatagramPacket p=new DatagramPacket(b,1024); ds.receive(p);
      • String s1=new String(p.getData(),0,p.getLength()); int n=Integer.parseInt(s1);
      • if(n%2==0)
        • System.out.println(n+ “is even”);
      • else
  • System.out.println(n+ “is odd”);
  • }

}

OUTPUT:

ClientUDP.java

ServerUDP.java

Program 1.5: Implement a Program for multi-client chat server.

Filename: chatClient.java:

import java.net.*; import java.io.*; import java.util.*; import java.awt.*;

class chatClient extends Frame implements Runnable

{

  • Socket soc;
  • TextField tf;
  • TextArea ta;
  • Button btnSend,btnClose; String sendTo;
  • String LoginName;
  • Thread t=null;
  • DataOutputStream dout;
  • DataInputStream din;
  • chatClient(String LoginName,String chatwith) throws Exception
  • {
    • super(LoginName); this.LoginName=LoginName; sendTo=chatwith;
    • tf=new TextField(50); ta=new TextArea(50,50);
    • btnSend=new Button(“Send”); btnClose=new Button(“Close”); soc=new Socket(“127.0.0.1”,5217);
    • din=new DataInputStream(soc.getInputStream()); dout=new DataOutputStream(soc.getOutputStream()); dout.writeUTF(LoginName);
    • t=new Thread(this); t.start();
  • }
  • void setup()
  • {
    • setSize(600,400);
    • setLayout(new GridLayout(2,1)); add(ta);
    • Panel p=new Panel(); p.add(tf); p.add(btnSend); p.add(btnClose); add(p);
    • show();
  • }
  • public boolean action(Event e,Object o)
  • {
    • if(e.arg.equals(“Send”))
    • {
      • try
      • {
        • dout.writeUTF(sendTo + “ ” + “DATA” + “ ” + tf.getText().toString()); ta.append(“\n” + LoginName + “ Says:” + tf.getText().toString()); tf.setText(“”);
      • }
      • catch(Exception ex)
      • {
      • }
    • }
    • else if(e.arg.equals(“Close”))
    • {
      • try
      • {
        • dout.writeUTF(LoginName + “ LOGOUT”); System.exit(1);
      • }
      • catch(Exception ex)
      • {
      • }
    • }
    • return super.action(e,o);
  • }
  • public static void main(String args[]) throws Exception
  • {
    • chatClient Client1=new chatClient(args[0],args[1]); Client1.setup();
  • }
  • public void run()
  • {
    • while(true)
    • {
      • try
      • {
        • ta.append(“\n” + sendTo + “ Says:” + din.readUTF());
      • }
      • catch(Exception ex)
      • {
        • ex.printStackTrace();
      • }
    • }
  • }}

Filename: chatServer.java

import java.net.*; import java.util.*; import java.io.*; class chatServer

{

  • static Vector ClientSockets; static Vector LoginNames; chatServer() throws Exception
  • {
    • ServerSocket soc=new ServerSocket(5217); ClientSockets=new Vector(); LoginNames=new Vector();
    • while(true)
    • {
      • Socket CSoc=soc.accept();
      • AcceptClient obClient=new AcceptClient(CSoc);
    • }
  • }
  • public static void main(String args[]) throws Exception
  • {
    • chatServer ob=new chatServer();
  • }

class AcceptClient extends Thread

{

  • Socket ClientSocket;
  • DataInputStream din;
  • DataOutputStream dout;
  • AcceptClient (Socket CSoc) throws Exception
  • {
    • ClientSocket=CSoc;
    • din=new DataInputStream(ClientSocket.getInputStream()); dout=new DataOutputStream(ClientSocket.getOutputStream()); String LoginName=din.readUTF();
    • System.out.println(“User Logged In:” + LoginName); LoginNames.add(LoginName); ClientSockets.add(ClientSocket);
    • start();
  • }
  • public void run()
  • {
    • while(true)
    • {
      • try
      • {

String msgFromClient=new String(); msgFromClient=din.readUTF();

  • StringTokenizer st=new StringTokenizer(msgFromClient); String Sendto=st.nextToken();
  • String MsgType=st.nextToken(); int iCount=0; if(MsgType.equals(“LOGOUT”))
  • {
    • for(iCount=0;iCount<LoginNames.size();iCount++)
    • {
      • if(LoginNames.elementAt(iCount).equals(Sendto))
      • {
      • LoginNames.removeElementAt(iCount); ClientSockets.removeElementAt(iCount); System.out.println(“User” + Sendto + “Logged Out ...”); break;
      • }
    • }}
    • else
    • {

  • String msg= “”; while(st.hasMoreTokens())
  • {
    • msg=msg+“ ”+st.nextToken();
  • }
  • for(iCount=0;iCount<LoginNames.size();iCount++)
  • {
    • if(LoginNames.elementAt(iCount).equals(Sendto))
      • {
        • Socket tSoc=(Socket)ClientSockets.elementAt(iCount);
        • DataOutputStream tdout=new DataOutputStream(tSoc.getOutputStream()); tdout.writeUTF(msg);
        • break;
      • }
    • }
    • if(iCount==LoginNames.size()) dout.writeUTF(“I am offline”);
    • else {}
  • }
  • if(MsgType.equals(“LOGOUT”))
  • {
    • break;
    • } }

    • catch(Exception ex)
  • {
  • ex.printStackTrace();
  • } } }
  • } }

OUTPUT:

ChatServer.java

ChatClient.java

ChatClient.java

Exercise 1: Develop a program for client server GUI chat.

Exercise 2: Implement a server which calculates sum of two numbers using Java Socket.