Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

SAMARA UNIVERSITY

COURSE TITTLE: DISTRIBUTED SYSTEMS


COURSE CODE: 4191

GROUP ASSIGNMENT

Submitted to:- Dr.sheik


dhabi.

Submission Date:-31/5/2021
1. Write a Program to Send and Receive a Message using
Connectionless Sockets

Java Socket Server

package com.journaldev.socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;

* This class implements java Socket server


public class SocketServer {

//static ServerSocket variable


private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9876;

public static void main(String args[]) throws IOException,


ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());

2
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the Server Socket object
server.close();
}

Java Socket Client

package com.journaldev.socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClientExample {

public static void main(String[] args) throws UnknownHostException,


IOException, ClassNotFoundException, InterruptedException{
//get the localhost IP address, if server is running on some other IP, you need
to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
for(int i=0; i<5;i++){
//establish socket connection to server

3
socket = new Socket(host.getHostName(), 9876);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
if(i==4)oos.writeObject("exit");
else oos.writeObject(""+i);
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
}

2. Code for the Datagram Sender and Receiver (Sends First,


Receives Next) Program
Steps the client needs to do to communicate with server:

1) Establish a client datagram socket //This statement creates a DatagramSocket


capable of sending and receiving datagram packets DatagramSocket clientSocket =
new DatagramSocket();

2) Send and receive packets Send Packet: DatagramPacket sendPacket =new


DatagramPacket(data,data_length, destination_IP_Address, destination_port_num
);

clientSocket.send( sendPacket ); Receive Packet byte data[] = new byte[ 100 ];

DatagramPacket receivePacket = new DatagramPacket( data, data_length );


clientSocket.receive( receivePacket );

4
5
6
3. How to write a Program for the Connection Server Program to
respond to a Connecting Client
Connection-Oriented – One connection is established between client and server –
Data flows in the communication channel in a continuous stream – Packets arrive
in order – Low probability of packet loss – TCP (Transmission Control Protocol) is
used for connection establishment and data transfer – In Java, this type of
communication is programmed using “Sockets”

start with some low level networking capabilities. • Connection Oriented


Communication is done in java using – Sockets • Connectionless oriented
Communication is done in java using

• Client uses server address and port number to get connected to server service

• Class “Socket” is used to establish communication between client and server

• Client has its own socket (S2)

• Client also has a corresponding socket at the server side (S1)

• Each socket has:

 Input Stream : to read data coming from destination

7
 Output Stream : to write data to destination

• Communication is done between input stream of one socket and the output
stream of the other socket

Steps the Client needs to do to communicate with server:

1) Connect to Server //This statement allows client to connect to server at “server


address” using port number port_number //The reference to communicate with
server is the “client Socket” at the server side Socket serverSocket = new
Socket(serverAddress, port);

2) Establish output stream to server //This statement get the output stream to
“clientSocket” at server side which help clients to send data to server PrintWriter
out = new PrintWriter(serverSocket.getOutputStream(), true);

3) Establish input stream to Server //This statement get the input stream to
“clientSocket” at server side which help client to receive data from server
BufferedReader input = new BufferedReader(new
InputStreamReader(serverSocket.getInputStream()));

After Server gets Client Socket and Client gets his own Socket, communication
starts between the two sockets using the input/output streams of sockets.

• Example1: – String message = input.readLine(); – This statement reads data


coming from destination

• Example2: – String message = “Send this text”; – out.println(message); – This


statement sends “message” to destination

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;

8
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Server {
public static final int port = 8081;
private static class ClientHandler implements Runnable {
private final Socket socket;
// All writes are performed while synchronized on 'os'.
private final PrintWriter os;
// Socket reads do not need to be synchronized as each clients gets its
// own thread.
private final BufferedReader is;
private final Map<String, ClientHandler> clients;
private String clientId;
public ClientHandler(Socket socket, Map<String, ClientHandler> clients)
throws IOException {
this.socket = socket;
this.clients = clients;
this.os = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream()));
this.is = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
}
@Override
public void run() {
try {
// First line the client sends us is the client ID.
clientId = is.readLine();
clients.put(clientId, this);
for (String line = is.readLine(); line != null; line = is.readLine()) {
int separatorIndex = line.indexOf(':');
if (separatorIndex <= 0) {

9
continue;
}
String toClient = line.substring(0, separatorIndex);
String message = line.substring(separatorIndex + 1);
ClientHandler client = clients.get(toClient);
if (client != null) {
client.sendMessage(clientId, message);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Client " + clientId + " terminated.");
clients.remove(clientId);
try {
socket.close();
} catch (IOException ioe) {
// TODO Auto-generated catch block
ioe.printStackTrace();
}
}
}
public void sendMessage(String from, String message) {
try {
synchronized (os) {
os.println(from + ":" + message);
os.flush();
}
} catch (Exception e) {
// We shutdown this client on any exception.
e.printStackTrace();
try {
socket.close();

10
} catch (IOException ioe) {
// TODO Auto-generated catch block
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException {
final Map<String, ClientHandler> clients = new ConcurrentHashMap<String, Clie
ntHandler>();
ServerSocket ss = new ServerSocket(port);
for (Socket socket = ss.accept(); socket != null; socket = ss.accept()) {
Runnable handler = new ClientHandler(socket, clients);
new Thread(handler).start();
}
}
}

11
REFERENCE

[1] Unix Network Programming, volumes 1-2 by W. Richard Stevens.

[2] TCP/IP Illustrated, volumes 1-3 by W. Richard Stevens and Gary R. Wright.

[3James F. Kurose, Keith W. Ross, “Computer Networking: A TopDown


Approach featuring the Internet”.

[4] Joseph M. Dibella , “Socket Programming with Java” 4.


[5]http://www.tutorialspoint.com/java/java_networking.htm 5.

[6]The Java Tutorials, “Lesson: All about Sockets”.

[7] Rajkumar Buyya, “Socket Programming”.

[8]http://en.wikipedia.org/wiki/Berkeley_sockets.

12

You might also like