Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
339 views

ITL331 Operating System and Network Programming Lab by Vinish Alikkal

The document describes experiments for an Operating Systems and Network Programming lab course. The experiments are divided into two sections - Operating System experiments implemented in C and Network Programming experiments implemented in Java. Some key Operating System experiments include process scheduling, inter-process communication, and memory management. The Network Programming experiments focus on network protocols, client-server programming, and network simulation.

Uploaded by

Vinish A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
339 views

ITL331 Operating System and Network Programming Lab by Vinish Alikkal

The document describes experiments for an Operating Systems and Network Programming lab course. The experiments are divided into two sections - Operating System experiments implemented in C and Network Programming experiments implemented in Java. Some key Operating System experiments include process scheduling, inter-process communication, and memory management. The Network Programming experiments focus on network protocols, client-server programming, and network simulation.

Uploaded by

Vinish A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

2022

ITL 331 OPERATING SYSTEM AND NETWORK PROGRAMMING LAB

Vinish Alikkal
Assistant Professor
1/1/2022
OPERATING SYSTEM
LIST OF EXPERIMENTS
(Experiments are to be implemented using C programming language)

1. Familiarization of system calls (fork, exec, getpid, exit, wait, close, stat etc) in
operating system.
2. Implement process scheduling algorithms (FCFS, SJF, Round-Robin, Priority) and
compute average waiting time and average turn-around time.
3. Inter-process communication using mail boxes, pipes, message queues and shared
memory.
4. Implementation of dining philosopher’s problem using threads, semaphores and
shared memory.
5. Implementation of banker’s algorithm.
6. Implement memory management schemes (first fit, best fit and worst fit).

NETWORK PROGRAMMING
LIST OF EXPERIMENTS
(Experiments are to be implemented using JAVA programming language)

7. Familiarization of Network Programming API in Java.


8. Implementation of Medium Access Control protocols –
1) Go Back N.
2) Selective Repeat
3) Sliding Window.
9. Implementation of an echo server.
10. Implement Client-Server communication using sockets.
11. Implementation of chat application
12. Install network simulator NS-3 in Linux operating system and simulate wired and
wireless scenarios. (Familiarization only)
INTRODUCTION TO NETWORK PROGRAMMING LAB

Aim: Familiarization of Network Programming API in Java.

NETWORKING BASICS

Computer networking is the engineering discipline concerned with communicationbetween


computer systems or devices. It is the practice of linking computing devices together with
hardware and softwarethat supports data communications across these devices.

KEY CONCEPTS AND TERMS

PACKET A message or data unit that is transmitted between communicating


processes.

A computer system that is accessed by a user working at a remote


HOST location. It is theremote process with which a process communicates. It
may also be referred as Peer.
Communication path created by establishing a connection between
CHANNEL endpoints

NETWORK A group of two or more computer systems linked together

In computer networking, a server is a computer designed to process


SERVER requests and deliverdata to other computers over a local network or the
Internet
A Client is an application that runs on a personal computer or
CLIENT workstation and relies on aserver to perform some operations

Network addresses give computers unique identities they can use to


NETWORK communicate with each other. Specifically, IP addresses and MAC
ADDRESS addresses are used on mosthome and business networks.

A Protocol is a convention or standard rules that enables and controls the


PROTOCOLS connection,communication and data transfer between two computing
endpoints.
An interface on a computer to which you can connect a device. It is a
PORT "logical connectionplace" and specifically, using the Internet's protocol,
TCP/IP.

A port is a 16-bit number, used by the host-to-host protocol to identify to


which higherlevel protocol or application program (process) it must
deliver incoming messages.

CONNECTION It defines the communication link between two processes.

CLIENT-SERVER MODEL

Network applications can be divided into two process: a Client and a Server, with
acommunication link joining the two processes.

Normally, from Client-side it is one-one connection. From the Server Side, it is many-
oneconnection.

The standard model for network applications is he Client-Server model. A Server is a process
thatis waiting to be contacted by a Client process so that server can do something for the
clientTypical BSD Sockets applications consist of two separate application level processes;
oneprocess (the client) requests a connection and the other process (the server ) accepts it.
SOCKET FUNCTIONS FOR ELEMENTARY TCP CLIENT/SERVER IN
CONNECTION-ORIENTED SCENARIO

The server process creates a socket, binds an address to it, and sets up a mechanism (called
alisten queue) for receiving connection requests. The client process creates a socket and requests
aconnection to the server process. Once the server process accepts a client process's request
andestablishes a connection, full-duplex (two-way) communication can occur between the
twosockets.

SOCKETS OVERVIEW

The operating system includes the Berkeley Software Distribution (BSD) interprocess
communication (IPC) facility known as sockets. Sockets are communication channels that
enableunrelated processes to exchange data locally and across networks. A single socket is one
endpoint of a two-way communication channel.

Sockets Overview:

In the operating system, sockets have the following characteristics:

 A socket exists only as long as a process holds a descriptor referring to it.


 Sockets are referenced by file descriptors and have qualities similar to those of
acharacter special device. Read, write, and select operations can be performed on
socketsby using the appropriate subroutines.
 Sockets can be created in pairs, given names, or used to rendezvous with other sockets
ina communication domain, accepting connections from these sockets or
exchangingmessages with them.
Sockets Background:

Sockets were developed in response to the need for sophisticatedinterprocess facilities to meet
the following goals:

 Provide access to communications networks such as the Internet.


 Enable communication between unrelated processes residing locally on a single
hostcomputer and residing remotely on multiple host machines.

Socket Facilities:

Socket subroutines and network library subroutines provide the buildingblocks for IPC. An
application program must perform the following basic functions to conductIPC through the
socket layer:

 Create and name sockets.


 Accept and make socket connections.
 Send and receive data.
 Shut down socket operations.

Socket Addresses:

Sockets can be named with an address so that processes can connect to them.Most socket
functions require a pointer to a socket address structure as an argument. Eachsupported protocol
suite defines its own socket address structure. The names of these structuresbegin with
sockaddr_ and end with a unique suffix for each protocol suite.Generic socket address structure:
Many of the Networking system calls require a pointer to asocket address structure as an
argument. Definition of this structure is in

#include<sys/socket.h>

structsockaddr {

unsigned short sa_family; /* address family : AF_xxx Value */

charsa_data[14]; /* up to 14 bytes of protocol- specific address */

};

Internet Socket address structure: The protocol specific structuresockaddr_in is identical in size to
generic structure which is 16 bytes
ELEMENTARY SOCKET SYSTEM CALLS

Socket() System Call: Creates an end point for communication and returns a descriptor.

Syntax

#include <sys/socket.h>

#include <sys/types.h>

int socket ( intAddressFamily, int Type, int Protocol);

Description: The socket subroutine creates a socket in the specified Address Family and of the
specified type. A protocol can be specified or assigned by the system. If the protocol is
leftunspecified (a value of 0), the system selects an appropriate protocol from those protocols in
theaddress family that can be used to support the requested socket type.

The socket subroutine returns a descriptor (an integer) that can be used in later subroutines that
operate on sockets.

Parameters AddressFamily Specifies an address family with which


addresses specified in later socket operations
should be interpreted. Commonly used
families are:
AF_UNIX
Denotes the Unix internal protocols
AF_INET
Denotes the Internet protocols.
AF_NS
Denotes the XEROX Network Systems
protocol.
Type Specifies the semantics of communication.
The operating system supports the following
types:
SOCK_STREAM
Provides sequenced, two-way byte streams
with a transmission mechanism for out-of-
band data.
SOCK_DGRAM
Provides datagrams, which are connectionless
messages of a fixed maximum length (usually
short).
SOCK_RAW
Provides access to internal network protocols
and interfaces. This type of socket is available
only to the root user.
SOCK_SEQPACKET
Sequenced packet socket

Protocol Specifies a particular protocol to be used with


the socket. Specifying the Protocol parameter
of 0 causes the socket subroutine to select
system’s default for the combination of family
and type.
IPROTO_TCP TCP Transport protocol
IPROTO_UDP UDP Transport protocol
IPROTO_SCTP SCTP Transport protocol

Return Values Upon successful completion, the socket subroutine returns an integer (the socket
descriptor). It returns -1 on error.

Bind( ) System call: Binds a name to a socket.

Description: The bind subroutine assigns a Name parameter to an unnamed socket. It assigns a
local protocol address to a socket.

Syntax

#include <sys/socket.h>
int bind (int sockfd, struct sockaddr *myaddr, int addrlen);

sockfd is a socket descriptor returned by the socket function. The second argument is a pointer to a protocol sp
third argument is size of this address structure.
There are 3 uses of bind:
a) Server registers their well-known address with a system. Both connection-oriented and
connection-less servers need to do this before accepting client requests.
b) A Client can register a specific address for itself.
c) A Connectionless client needs to assure that the system assigns it some unique address, so that
the other end (the server) has a valid return address to send its responses to.

Return Values: Upon successful completion, the bind subroutine returns a value of 0. Otherwise, it
returns a value of -1 to the calling program.

connect() System call:


The connect function is used by a TCP client to establish a connection with
a TCP server.
#include <sys/socket.h>
int connect(int sockfd, struct sockaddr *servaddr, int addrlen);
sockfd is a socket descriptor returned by the socket function. The second and third arguments are
a pointer to a socket address structure and its size. The socket address structure must contain the
IP address and port number of the server.

Return Values: Upon successful completion, the connect subroutine returns a value of 0.
Otherwise, it returns a value of -1 to the calling program.

listen() System call

This system call is used by a connection-oriented server to indicate that it is willing to receive
connections.

#include <sys/socket.h>

int listen (int sockfd, int backlog);

is usually executed after both the socket and bind system calls, and immediately before accept
system call. The backlog argument specifies how many connections requests can be queued by
the system while it waits for the server to execute the accept system call.

Return values: Returns 0 if OK, -1 on error

accept() System call:

The actual connection from some client process is waited for by having the server execute the
accept system call.
#include <sys/socket.h>
int accept (int sockfd, struct sockaddr *cliaddr, int *addrlen);

Send( ),sendto( ),recv( ) and recvfrom( ) system calls:


These system calls are similar to the standard read and write functions, but one additional
argument is required.
Go Back N.

Aim: Implementation of Medium Access Control protocols – 1) Go Back N.

DESCRIPTION:

The sender window size is N in GBN. For example, if it is Go Back 10 (GB10) it indicates
that the window size of the sender is 10. In GBN, the window size of the receiver is always
equal to 1 irrespective of the size of the sender. GBN uses cumulative acknowledgments. At
the receiver’s end, it starts an acknowledgment timer. The receiver sends an
acknowledgment for the set of finite frames received once the timer ends. If the
acknowledgment is not sent, then the set of frames has to be retransmitted from the sender.

The acknowledgment timer will not start once the earlier timer expires. It starts once it
receives a packet or a frame.

It will be more clear once we take an example.

Let’s say it is GB3 with a sequence number field of 2 bits. The size of the sender
window=3 (since N=3). We require a minimum of 3 sequence numbers to represent
the frames.
Now the sender sends three frames at once (window size=3). Then the window
slides to the left of three frames. The receiver responds with an increased value of
the acknowledgment number stating that it is waiting for the “acknowledgment
number” frame. Suppose if frames 0,1,2 are transmitted. If there is no loss of
packets, then the receiver responds with ACK=3 (n+1) asking for the transmission
of frame 3. With reference to Fig 1.

If there is any loss in the frame, say 1 is lost when 0,1, and 2 are transmitted. The
window is slid to the next three frames at the sender’s side. Since the frame 1 is
lost, the receiver waits for the frame 1 until the timer expires. When the timer
expires, the acknowledgment number sent is 1, as only the frame 0 is received at
the receiver side and the other frames are simply discarded. Then the “window
slides back to the frame 1” or “window go back to frame 1” and transmit all the
frames starting from frame 1 i.e. 1,2, and 3.

The frames are now transmitted completely with no loss and the acknowledgment
number would be ACK+1 i.e. 4. Now, what if the ACK packet is lost??
Acknowledgment lost

The sender waits for the acknowledgment until the timer expires. If the
acknowledgment is not received, then the window slides to the initial or the earlier
set of frames and retransmits them. As the receiver is now waiting for frame 3
(assuming 0,1, and 2 frames are transmitted earlier), it simply discards them and
sends the acknowledgment number 3 again. This process continues until the
reception of respective packets take place at both ends of the communication.

PROGRAM:

import java.io.*;
public class GoBackN {

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


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter the Window Size: ");


int window = Integer.parseInt(br.readLine());

boolean loop = true;


int sent = 0;

while(loop)
{

for(int i = 0; i < window; i++)


{
System.out.println("Frame " + sent + " has been transmitted.");
sent++;
if(sent == window)
break;
}

System.out.println("Please enter the last Acknowledgement received.");


int ack = Integer.parseInt(br.readLine());

if(ack == window)
loop = false;
else
sent = ack;
}

OUTPUT:

Please enter the Window Size:


7
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Please enter the last Acknowledgement received.
3
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Please enter the last Acknowledgement received.
5
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Please enter the last Acknowledgement received.
7
SELECTIVE REPEAT

Aim: Implementation of Medium Access Control protocols - Selective Repeat

DESCRIPTION:

Selective repeat protocol is a sliding window protocol that uses the concept of
pipelining where multiple packets can be sent while the sender is waiting for the
acknowledgement for the first sent packet. The selective repeat protocol manages
error and flows control between the sender and receiver.

Working of Selective Repeat Protocol

Like go-back-n, selective repeat protocol is also a sliding window protocol. Unlike
the go-back-n protocol, the selective repeat protocol resends only a selective packet
that is either lost or corrupted. Let us first discuss the windows in selective repeat.

Window

In selective repeat, both sender and receiver have a sliding window. On the sender
side, the window covers the sequence of packets that are either sent or can be sent.
At the receiver, the sliding window covers the sequence number of the packets that
are either received or are expected to be received. In selective repeat, the size of the
sender and receiver window is the same. Let us study the sender window and
receiver window in brief.

1. Sender Window

The sender window in selective repeat is much smaller as compared to the go-back-
n protocol. The size of the sender window here is 2m-1. Here m is the number of bits
used by the packet header to express the sequence number of the corresponding
packet.

The sender window covers the packets that are sent but not yet acknowledged, one
that is acknowledged out of order and the one that can be sent once the data for the
corresponding are received by the sender’s application layer.

2. Receiver Window
The maximum size of the receiver window is 2m-1 which is the same as the sender
window. The receiver window covers the sequence number of the packets that are
received out of order and are waiting for the packets that were sent earlier but are
not yet received.

The receiver transport layer does not deliver packets out of order to the application
layer. It waits until a set of consecutive packets are received so that they can be
delivered to the application layer
ALGORITHM:

SERVER

ALGORITHM:

1. Start.
2. Establish connection (recommended UDP)
3. Accept the window size from the client(should be <=40)
4. Accept the packets from the network layer.
5. Calculate the total frames/windows required.
6. Send the details to the client(totalpackets,totalframes.)
7. Initialise the transmit buffer.
8. Built the frame/window depending on the windowsize.
9. Transmit the frame.
10. Wait for the acknowledgement frame.
11. Check for the acknowledgement of each packet and repeat the
process for the packet for which the negative acknowledgement
isreceived.
Else continue as usual.
12. Increment the frame count and repeat steps 7 to 12 until all packets
are
transmitted.
13. Close the connection.
14.Stop.

CLIENT
ALGORITHM

* The algorithm for this module process is as……………………


1. Start.
2. Establish a connection.(recommended UDP)
3. Send the window size on server request.
4. Accept the details from the server(totalpackets,totalframes).
5. Initialize the receive buffer with the expected packets.
6. Accept the frame/window from the server.
7. Check for validity of the packets and construct the
acknowledgement frame
depending on the validity.(Here the acknowledgement is accepted
from the
users)
8. Depending on the acknowledgement frame readjust the process.
9. Increment the frame count and repeat steps 5-9 until all packets
are received.
PROGRAM

//................CLIENT SIDE (SELECTIVE REPEAT).............//

import java.lang.System;
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.Random;
import java.util.*;

public class cli {


static Socket connection;

public static void main(String a[]) throws SocketException {


try {
int v[] = new int[10];
int n = 0;
Random rands = new Random();
int rand = 0;

InetAddress addr = InetAddress.getByName("Localhost");


System.out.println(addr);
connection = new Socket(addr, 8011);
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
DataInputStream in = new DataInputStream(
connection.getInputStream());
int p = in.read();
System.out.println("No of frame is:" + p);

for (int i = 0; i < p; i++) {


v[i] = in.read();
System.out.println(v[i]);
//g[i] = v[i];
}
rand = rands.nextInt(p);//FRAME NO. IS RANDOMLY
GENERATED
v[rand] = -1;
for (int i = 0; i < p; i++)
{
System.out.println("Received frame is: " + v[i]);

}
for (int i = 0; i < p; i++)
if (v[i] == -1) {
System.out.println("Request to retransmit from
packet no "
+ (i+1) + " again!!");
n = i;
out.write(n);
out.flush();
}

System.out.println();

v[n] = in.read();
System.out.println("Received frame is: " + v[n]);

System.out.println("quiting");
} catch (Exception e) {
System.out.println(e);
}

}
}
OUTPUT

[root@localhost sinhgad]# java cli

Localhost/127.0.0.1

No of frame is:8

30

40

50

60

70

80

90

100

Received frame is: 30

Received frame is: 40

Received frame is: 50

Received frame is: -1

Received frame is: 70

Received frame is: 80

Received frame is: 90

Received frame is: 100

Request to retransmit from packet no 4 again!!

Received frame is: 60

quiting
/.....................SERVER SIDE (SELECTIVE REPEAT)..........//

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.net.SocketException;

public class ser

static ServerSocket Serversocket;

static DataInputStream dis;

static DataOutputStream dos;

public static void main(String[] args) throws SocketException

try

int a[] = { 30, 40, 50, 60, 70, 80, 90, 100 };

Serversocket = new ServerSocket(8011);

System.out.println("waiting for connection");

Socket client = Serversocket.accept();

dis = new DataInputStream(client.getInputStream());


dos = new DataOutputStream(client.getOutputStream());

System.out.println("The number of packets sent is:" + a.length);

int y = a.length;

dos.write(y);

dos.flush();

for (int i = 0; i < a.length; i++)

dos.write(a[i]);

dos.flush();

int k = dis.read();

dos.write(a[k]);

dos.flush();

catch (IOException e)

System.out.println(e);

finally

try
{

dis.close();

dos.close();

catch (IOException e)

e.printStackTrace();

OUTPUT

[root@localhost sinhgad]# java ser

waiting for connection

The number of packets sent is:8


SLIDING WINDOW

Aim: Implementation of Medium Access Control protocols - Sliding Window.

Sliding window protocols are data link layer protocols for reliable and sequential
delivery of data frames. The sliding window is also used in Transmission Control
Protocol.
In this protocol, multiple frames can be sent by a sender at a time before receiving
an acknowledgment from the receiver. The term sliding window refers to the
imaginary boxes to hold frames. Sliding window method is also known as
windowing.
Working

In these protocols, the sender has a buffer called the sending window and the
receiver has buffer called the receiving window.

The size of the sending window determines the sequence number of the outbound
frames. If the sequence number of the frames is an n-bit field, then the range of
sequence numbers that can be assigned is 0 to 2𝑛−1. Consequently, the size of the
sending window is 2𝑛−1. Thus in order to accommodate a sending window size of
2𝑛−1, a n-bit sequence number is chosen.

The sequence numbers are numbered as modulo-n. For example, if the sending
window size is 4, then the sequence numbers will be 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, and so
on. The number of bits in the sequence number is 2 to generate the binary sequence
00, 01, 10, 11.

The size of the receiving window is the maximum number of frames that the
receiver can accept at a time. It determines the maximum number of frames that
the sender can send before receiving acknowledgment.

Example

Suppose that we have sender window and receiver window each of size 4. So the
sequence numbering of both the windows will be 0,1,2,3,0,1,2 and so on. The
following diagram shows the positions of the windows after sending the frames and
receiving acknowledgments.
PROGRAM

CLIENT PROGRAM

import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(10);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{

System.out.println("Enter "+nf+" Messages to be send\n");


for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received");
ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window size");
break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine(); p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
SERVER PROGRAM

import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch; System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT:

//CLIENT SIDE OUTPUT

Enter the no. of frames : 4


Enter 4 Messages to be send

hiii
how r u
i am fine
how is evryone
Acknowledgment received for 4 frames

Do you wants to send some more frames : no

//SERVER SIDE OUTPUT

The received Frame 0 is : hiii


The received Frame 1 is : how r u
The received Frame 2 is : i am fine
The received Frame 3 is : how is evryone

Acknowledgment sent
ECHO SERVER.

Aim: Implementation of an echo server.

DESCRIPTION:

An EchoServer is an application that allows a client and a server to connect so a


client can send a message to the server and the server can receive the message
and send, or echo, it back to the client.

Server
A server is a computer or computer program that provides a service to another
computer, or client. For example, the internet is based on web servers that
respond to requests from clients via web browsers. How do you connect to a server
to access it services? Often, you will connect to a server over a computer network,
which is a group of computers connected together in order to share resources. To
connect to a server, you need to know the port number that the server socket is
listening on, which is an endpoint for communication between the client and the
server. Each port number is associated with an IP address, a numerical label
assigned to each device connected to a computer network, and a protocol type,
preset rules and guidelines for communicating data. With the port number and IP
address, you can attempt to establish a connection to a server. It is important to
note that when building an echo server, it is not a requirement to be connected
within a network. The server can be run locally on a computer and a client can
connect to the server via the same computer.

Client
A client is responsible for sending a message to the server, and is also where the
message is echoed back to. Once the server is running, or listening for connections,
a client is able to send a request to the server. With the correct port number and
IP address, and if everything goes to plan, the server accepts the connection and
creates a new socket. Through the newly created socket, the client and server can
now communicate by writing to or reading from the socket.
Dealing with Input and Output
In order to build an echo server that receives a client message and echoes it back
to the client, getting the input and output streams from a connected socket is
necessary for creating the communication channels between the client and server.
These streams are flows of data that mean the client can now send messages to
the server, and the server can echo back the message to the client. In Java, we can
create this communication channel by
calling .getInputStream() and .getOutputStream() on the socket. The input stream
allows data to flow from the client to the server, whilst the output stream allows
the server to send data back to the client.
Now we have established the communication channels, how to do we actually take
some input from the client, write that to the InputStream, read from
theInputStream and then send that input back to the client via
the OutputStream?
To write to and read data from the input channel, we can use Java
classes Scanner or BufferReader. Both allows for the ability to read user input
from the command line. Whilst Scanner parses, or converts, input data (strings or
primitive types) using regular expressions, BufferReader simply reads the
characters.

Java Socket programming is used for communication between the applications


running on different JRE. Java Socket programming can be connection-oriented or
connection-less. Socket and ServerSocket classes are used for connection-oriented
socket programming and DatagramSocket and DatagramPacket classes are used
for connection-less socket programming.

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number
SERVER PROGRAM:

import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[]) throws Exception,UnknownHostException{

ServerSocket ss=new ServerSocket(8088);

Socket s=ss.accept();;

DataInputStream din=new DataInputStream(s.getInputStream());


DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(str!="stop")
{
System.out.println("Waiting for client's Reply...");
str=din.readUTF();
System.out.println("Client: "+str);
System.out.println("Enter Message:");
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}

din.close();
s.close();
ss.close();
}
}
CLIENT PROGRAM:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {

Socket s=new Socket("localhost",8088);

DataInputStream din=new DataInputStream(s.getInputStream());


DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){
System.out.println("\nEnter Response: ");
str=br.readLine();
dout.writeUTF(str);
dout.flush();
System.out.println("Waiting for Server's Reply...");
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();

}
}

OUTPUT:
SERVER SIDE:

Waiting for client’s reply…


Client: Hai….
Enter Message:
hellooo
Waiting for client’s reply…
This is Client
Enter Message:
This is Server
Waiting for client’s reply…
Client: Stop
Enter Message:
Stop

CLIENT SIDE

Enter Response:
Hai…
Waiting for Server’s Reply …
Server says: hellooo
Enter Response:
This is Client
Waiting for Server’s Reply …
Server says: This is Server
Enter Response:
Stop
Waiting for Server’s Reply …
Server says: Stop
CLIENT-SERVER COMMUNICATION

Aim: Implement Client-Server communication using sockets.

DESCRIPTION:

Socket programming is used for communication between the applications running on


different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and prints it.
Here, two classes are being used: Socket and ServerSocket. The Socket class is used to
communicate client and server. Through this class, we can read and write message. The
ServerSocket class is used at server-side. The accept() method of ServerSocket class
blocks the console until the client is connected. After the successful connection of client,
it returns the instance of Socket at server-side.
PROGRAM:

CLIENT SIDE

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

public class MyClient {


public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

dout.writeUTF("Hello Server");
dout.flush();

dout.close();
s.close();

}catch(Exception e)
{
System.out.println(e);
}
}
}

SERVER SIDE

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

public class MyServer {


public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

String str=(String)dis.readUTF();
System.out.println("message= "+str);

ss.close();

}catch(Exception e){System.out.println(e);}
}
}
OUTPUT

SERVER SIDE

message=Hello Server

CLIENT SIDE

You might also like