You are on page 1of 8

RATHWA SONAL

190130116059 Computer Networks (3150710)

PRACTICAL:02
Page | 1
AIM: implement client server using socket program in
any convenient language.

The entire process can be broken down into following steps:

IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

Server side :

Page | 2

import java.net.*;
import java.io.*;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
in=newDataInputStream(new
BufferedInputStream(socket.getInputStream()));

IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

String line = ""; Page | 3

while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
socket.close();
in.close();
}
catch(IOException i)
{
IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

System.out.println(i); Page | 4

}
}
public static void main(String args[]){
Server server = new Server(5000);
}
}

Client side:

import java.net.*;
import java.io.*;
public class Client
{
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
public Client(String address, int port)
{
try
IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

{
socket = new Socket(address, port);
System.out.println("Connected"); Page | 5

input = new DataInputStream(System.in);


out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
String line = "";
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);

IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

}
catch(IOException i)
{ Page | 6

System.out.println(i);
}
}
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[]) {
Client client = new Client("127.0.0.1", 5000);
}
}

IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

Server output :

Page | 7

Client output:

IT-A3
RATHWA SONAL
190130116059 Computer Networks (3150710)

Server output:

Page | 8

Client output:

IT-A3

You might also like