You are on page 1of 56

VIDYA ACADEMY OF SCIENCE & TECHNOLGY

Thalakkottukara
Thrissur, Kerala 680 501
Ph. (91) 04885 287751, 287752
www.vidyaacademy.ac.in

(Approved by AICTE & Affiliated to University of Calicut)

A unit of
Vidya International Charitable Trust

CS09708(P):NETWORKPROGRAMMINGLAB
Teacher'sCopy
SYLLABUS

Teaching scheme Credits: 2

3 hours practical per week

Objectives

*To teach the working of various networking protocols

Lab 1 : Implementation of PC to PC file transfer using serial port and MODEM.

Lab 2,3 : Software Simulation of IEEE 802.3, 802.4 and 802.5 protocols.

Lab.4,5 : Software Simulation of Medium Access Control protocols

1) GoBackN,

2) Selective Repeat and

3) Sliding Window.

Lab 6 : Implementation of a subset of Simple Mail Transfer Protocol using UDP.

Lab 7,8 : Implementation of a subset of File Transfer Protocol using TCP/IP

Lab 9 : Implementation of "finger" utility using Remote Procedure Call (RPC)

Lab.10 : Generation and processing of HTML forms using CGI.

Reference Books

1. S Richard S.W., Unix Network Programming, Prentice Hall India


2. Comer D.E., Internetworking with TCP/IP, Vol. 1,2 & 3, Prentice Hall India
3. Campione et. al M., The Java Tutorial Continued, Addison Wesley
Internal Continuous Assessment (Maximum Marks-50)
60%-Laboratory practical and record
30%- Test/s
10%- Regularity in the class

VAST Dept of Computer Science & Eng. (1)


INDEX

NameofExperiment PageNo

I.Description 03

II.Programs

UniversityPrescribedlabExperiments
1.SocketProgrammingusingTCP 06
2.SocketprogrammingusingUDP 08
3.BidirectionalCommunicatiousingTCP 10
4.BidirectionalCommunicationusingUDP 14
5.BroadcastingusingTCP 17
6.PublicChat 20
7.FileTransferProtocol 23
8.StopandWaitProtocol 28
9.GoBackNProtocol 32
10.FingerUtility 37
11.CommonGatewayInterface 40
AdvancedExperiments
12.Dateserverandclient 43
13.Slidingwindowprotocols 45

DesignExperiments
14.Remotemethodinvocationnetwork 49
15.Pingcommand 51

OpenEndedExperiments 54

VAST Dept of Computer Science & Eng. (2)


INTRODUCTIONTONETWORKPROGRAMMING
Networkapplicationareeverywhere.Anytimeyoubrowsetheweb,sendanemailmessageorpop
upanxwindow,youareusinganetworkapplication.Interstinglyallnetworkapplicationsarebasedonthesame
basicprogrammingmodel,havesimilaroveralllogicalstructuresandrelyonthesameprogramminginterface.We
willneedtounderstandthebasicclientserverprogrammingmodelandhowtowriteclientserverprograms,that
usetheserviceprovidedbytheinternet.
CilentServerProgrammingmodel
Theclientservermodelisadistributedapplicationstructureincomputingthatpartitionstasksor
workloadsbetweentheprovidersofaresourceorservice,calledservers,andservicerequesters,calledclients.
Oftenclientsandserverscommunicateoveracomputernetworkonseparatehardware,butbothclientandserver
mayresideinthesamesystem.Aserverisahostthatisrunningoneormoreserverprogramswhichsharetheir
resourceswithclients.Aclientdoesnotshareanyofitsresources,butrequestsaserver'scontentorservice
function.Clientsthereforeinitiatecommunicationsessionswithserverswhichawaitincomingrequests.the
fundamentaloperationsintheservermodelisgivenbelow(fig1)

1.Clientsendsrequest 2.ServerProcesses
request
Client Process Server Process Resources
3.Serversendsresponse

Fig1.ClientServerTransaction

AClientServertrancsactionconsistoffoursteps
1.Whenaclientneedsserver,initiatesatransactionsbysendingarequesttotheserver.Foreg,whena
webbrowserneedsafile,itsendsarequesttoawebserver
2.Theserverrecievestherequest,interpretitandmanipulatesitsresourcesintheappropriateway.For
eg,whenawebserverreceivesarequestfromabrowser,itreadsadiskfile
3.Theserversendsaresponsetotheclient,andthenwaitsforthenextrequest,foreg,thewebserver
sendsafilebackto aclient.
4.Theclientrecievestheresponseandmanipulatesit.Foreg,afterawebbrowserrecievesapagefrom
theserver,itdisplaysitonthescreen
itisimportanttorealizethatclientandserversareprocessandnotmachinesorhostsastheyareoften
calledinthiscontext.Asinglehostcanrunmanydifferentclientandsererconcurrentlyandaclientandserver
transactioncanbeonthesameordifferenthost.Theclientservermodelisthesameregardlessofthemappingof
clientsandservertohost
Therearetwotypesofclientsserverapplication.Onetypeisaclientserverapplicationthat
implementationofaprotocolstandarddefinedinanRFC(RequestForCommand)
forsuchanimplementation,thecleintandserverprogramsmustconformtotherulesdeclared
byRFC.forex,theclientprogramcouldbeanimplementationoftheFTPserver.Ifonedeveloperwritescodefor

VAST Dept of Computer Science & Eng. (3)


theclietntprogramcouldbeimplementationandanindependentdeveloperswritecodefortheserverprogram.
AndbothdevelopercarefullyfollowtherulesoftheRFCthenthetwoprogramswillbeabletointeroperateindeed
,mostoftodaysnetworkapplicarioninvolveconnectionbetweenclientandserverprogramsthathavebeen
createdbyindependentdeveloper.whenaclientorserverprogramimplementsaprotocoldefinedinanRFC,it
shouldusetheportnumberallocatedwithheprotocol.
Theoldersortofclientserverapplicationisaproprietaryclientserverapplication.Inthiscase
theclientandserverprogramsdonotnecessaryilyconformtoanyexistingRFC.Asingledeveloper(development
team)createsboththeclientandserverprogramsandthedeveloperhascompletecontroloverwhatgoesinthe
code.Butbecausethecodedoesnotimplementapublicdomainprotocolotherindepedentdeveloperwillnotbe
abletodevelopcodethatinteroperatewiththeapplication.Thedevelopermustbecarefulnottooneoftheewell
knownportnumberdefindintheRFC'S(255msp,80HTTPetc).
wewriteTCP&UDPapplicationinjava.Wecouldhavewritenthecodeincorc++,but
weoptedfotjavaforseveralreasons.First,theapplication'saremoreneatlyandclearlywriteninjava.Withjava
therearefewerlinesofcodeandeachlinecanexplaineedtotheprogrammerwithoutmustdifficultysecond
,clientserverprogramminginjavaisbecomingincreamilypopularandmaybecomethenorminupcoming
years.Javaisplatformindependent.Ithasexpectionmechanism'sforrobusthandlingofcommonproblemthat
occurduringI/Oandnetworingoperattions,andanditsthreadingfaullic
provideawaytoeassilyimplmentpowerfulserver.javaprovidearichlibraryofnetworksenabledclassthaallows
applicationtoreadyaccesnetworkservervices.Therearetwotoolsavailableforcommunication.
1,socketthattusesTCP/IP
2,SocketsthatusesUDP

SocketprogramingwitthTCP/IP
processrunningondifferentmachinesconnwitheachotherbysendingmessageintosockets.Wesaid
thateachprocesssocketisanalogoustoahouseandtheprocess'ssocketisanalogoustoadoorasshownin
fig.2.ThesocketisanalogoustoadoorbetweenapplicationprocessandTCP.Theapplicationdeveloperhascontrol
ofeverythingontheapplicationlayersideofsocket.However,ithaslittlecontrolofthetransportlayerside.

socket Socket

TCP with Buffers TCP with buffer


Process Process
and variables Internet and variables

Controlled by Controlled by Controlled by Controlled by


Application Operating Operating Application
developer System System developer
Host Host

Fig.2ProcessCommunicatingthroughTCPports

VAST Dept of Computer Science & Eng. (4)


Nowlet'stoalittlecloserlookattheinteractionofclient&serverprograms.Theclienthasthejobof
initiatingcontactwiththeserver.Inorderoftheservertotheabletoreacttotheclientsinitialcontact,theserver
hastobeready.Thisimpliestwothings.First,theserverprogramscannotbedormant,itmustberunningasa
processbeforetheclientattempt,havesomesortofdoor(ip,socket)thatwelcomesomeinitialcontactfromaclient.

Withtheserverprogramrunning,theclientprocesscaninitiateaTCPconnectiontotheserver.Thisisdone
intheclientprogrambycreatingasocketobject,whentheclientcreatessocketobject,itspecifytheaddressofthe
serverprocess,namelytheipaddressoftheserverandtheportnumberoftheprocess.
Duringthethreewayhandshaketheclientprocessknocksonthewelcomingdooroftheserver
process.Whentheserverhearstheknocking.Ifcreateanewdoorthatparticularclientfromtheapplication
perspective,theTCPconnectionisadirectvitualpipebetweentheclientssocketandsentarbitrarybytesintoits
socket.Clientprocesscansendarbitrarybytesintoitssocket,theclientprocesscansend.TheTCPguarenteesthat
theserviceprocessuntillreceiveeachbytesintheordersend.Theclientprocesscanalsoreceivebytesfromits
socketandserverprocesscanalsosendbytesintoitsconnectionsocket.Itillustratefig.3
Becausesocketplayacentralroleinclientserverapplication,clientserverapplicationdevelopment.Italso
referredassocketprogramming.

Welcoming Socket
ake
Handsh
3- w ay
Client Socket

bytes
Connection Socket

bytes

Fig.3Clientsocket,welcomingsocketandconnectionsocket
SocketProgrammingwithUDP
WelearnedintheprevioussectionthatwhentwoprocesscoomunicateoverTCP,fromtheperspectiveover
theprocessitisasifthereisapipebetweenthetwoprocess.Thispiperemainsinplaceuntilloneoftheprocess
closeit.Whenoneoftheprocesswantstosendsomebytestotheotherprocess,itsimplyinsertedthebytesintothe
pipe.
UDPalsoallowtwoprocessesrunningondifferenthoststocommunicate.UDPdifferfromTCPinmany
fundamentalways.UDPisconnectionlessservice.Thereisnotaninitialhandshakingphaseduringwhichapipeis
establishedbetweenthetwoprocess.BecauseUDPdoesnothaveapipe,whenaprocesswantstosendabactchof
bytestoanotherprocess,thesendingprocessmustbeexcludeattachthedestinationprocess.
Sftercreatingapacket,thesendinfprocesspushesthepacketintothenetworkthroughasocket
continuewithoutfax,waitingforpacket,thefaxthendrivesthepacketinthedirectionofthepacketdestination
address.However,thefaxdoesnotguarenteethatitwilleventuallygetthedatagramtoitsultimatedestination,
inUDPthereis:
1.nointialhandshakingbetweentwoprocesses,andthereforenoneedforawelcomingsocket
2.nostreamsaeattachedtothesocket
3.thesendinghostcreatespacketbyattachingtheIPaddressandportnumbertoeachbatchofbytesitsends
4.Thereceivingprocessmustunreaveltoreceivedpacketstoabtainthepacketsinformationbytes

*********

VAST Dept of Computer Science & Eng. (5)


Exp:1
SOCKETPROGRAMMINGUSINGTCP

Aim:

WriteaprogramtoimplemnttheSocketProgrammingusingTCPwhereaclientreadsastringandpassittothe
serverandtheserverconvertedittouppercaseandsendbacktotheclient.Theoutputwillbedisplayedatclient
side.

Algorithm:

TCPserver

step1:start
step2:initializeserversocket
step3:repeatthestep4tostep10
step4:checkthesocketisconnectedbyaclientornot
step5:ifclientconnectedthenprintclientconnected
step6:readthedatafromtheclientbyusingabufferedreader
step7:convertthereadedstringintocapitalstring
step8:sendthecapitalstringintoclientbyusingdataoutoutstream
step9:stop

TCPClient

step1:start
step2:readthestringfromkeyboardandstoredintoavariableinformuser
step3:connecttotheserversocket
step4:sendthevaribleinformusertoserverbyusingdataoutputstream
step5:readthecapitalstringfromtheserverbyusingbufferedreader
step6:readthedatafromtheclientbyusingabufferedreader
step7:printthestringreturnedfromtheserver
step8:closetheclientsocket
step9:stop

Program:

TCPclient.java

importjava.io.*;
importjava.net.*;
classTCPclient
{
publicstaticvoidmain(String[]args)throwsException
{
Stringsentence;
StringmodSentence;
BufferedReaderFromUser_in=newBufferedReader(new InputStreamReader(System.in));
SocketclientSocket=newSocket("localhost",6788);
System.out.println("Pleaseenterthemessagetobeconverted:");

VAST Dept of Computer Science & Eng. (6)


DataOutputStreamToServer_out=new
DataOutputStream(clientSocket.getOutputStream());
BufferedReaderinFromServer=newBufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence=FromUser_in.readLine();
ToServer_out.writeBytes(sentence+'\n');
modSentence=inFromServer.readLine();
System.out.println("ConvertedmessagefromServer:"+modSentence);
clientSocket.close();
}
}

TCPserver.java

importjava.io.*;
importjava.net.*;
classTCPserver
{
publicstaticvoidmain(String[]args)throwsException
{
StringclSentence;
StringcapSentence;
ServerSocketSocket_welcome=newServerSocket(6788);
try
{

while(true)
{
SocketconnectionSocket=Socket_welcome.accept();
BufferedReaderinFromClient=newBufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
System.out.println("Waitingformessagefromclient.....");
DataOutputStreamoutToClient=new
DataOutputStream(connectionSocket.getOutputStream());
clSentence=inFromClient.readLine();
capSentence=clSentence.toUpperCase()+'\n';
outToClient.writeBytes(capSentence);
System.out.println("Messageconvertedsuccessfully");
connectionSocket.close();
Socket_welcome.close();
}
}catch(Exceptione){}
}
}

Output:

sampledata..
FROMSERVER:SAMPLEDATA..

VAST Dept of Computer Science & Eng. (7)


Exp:2
SOCKETPROGRAMMINGUSINGUDP
Aim:

WriteaprogramtoimplemnttheSocketProgrammingusingUDPwhereaclientsendsastringandpassittothe
serverandtheserverconvertedittouppercaseandsendbacktotheclient.Theoutputwillbedisplayedatclient
side.

Algorithm:

UDPserver

step1:start
step2:initializeadatagramsocket
step3:repeatthestep4tostep10
step4:ifadatagramsocketarrivedthenitisreceivedbyserversocket
step5:readthedatafromthereceivedpacket
step6:readtheIPaddressandportnumberfromthereceivedpacket
step7:convertthereadedstringintocapitalstring
step8:sendthecapitalstringintoclientthroughthedatagram
step9:stop

TCPClient
step1:start
step2:readthestringfromkeyboardandstoredintoavariableinformuser
step3:assignIpaddresstoclientasinetaddress
step4:createadatagramsocket
step5:createadatagrampacketwithreadedstring,IPaddress
step6:sendthedatagrampackettoserver
step7:receivethedatagrampacketfromtheserver
step8:readthedatafromthedatagrampacket
step9:printthestring
step10:closetheserver
step11:stop

Program:

UDPclient.java

importjava.io.*;
importjava.net.*;
classUDPclient
{
publicstaticvoidmain(Stringargs[])throwsException
{
System.out.println("Enterthedatatobemodified:");
BufferedReaderFromUser_in=newBufferedReader(newInputStreamReader(System.in));
DatagramSocketclientSocket=newDatagramSocket();
InetAddressIPAddress=InetAddress.getByName("localhost");
byte[]sendData=newbyte[1024];
byte[]receiveData=newbyte[1024];
Stringsentence=FromUser_in.readLine();

VAST Dept of Computer Science & Eng. (8)


sendData=sentence.getBytes();
DatagramPacketsendPacket=newDatagramPacket(sendData,sendData.length,IPAddress,9877);
clientSocket.send(sendPacket);
DatagramPacketreceivePacket=newDatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
StringmodSentence=newString(receivePacket.getData());
System.out.println("MessagecovertedbySERVER:"+modSentence);
clientSocket.close();
}
}

UDPserver.java

importjava.io.*;
importjava.net.*;
classUDPserver
{
publicstaticvoidmain(Stringargs[])throwsException
{
DatagramSocketserverSocket=newDatagramSocket(9877);
byte[]receiveData=newbyte[1024];
byte[]sendData=newbyte[1024];
System.out.println("Waitingforclient....");

try{
while(true)
{

DatagramPacketreceivePacket=newDatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
Stringsentence=newString(receivePacket.getData());
InetAddressIPAddress=receivePacket.getAddress();
intport=receivePacket.getPort();
StringcapSentence=sentence.toUpperCase();
sendData=capSentence.getBytes();
DatagramPacketsendPacket=newDatagramPacket(sendData,sendData.length,
IPAddress,port);
serverSocket.send(sendPacket);
System.out.println("Messageconverted:");
serverSocket.close();
}
}catch(Exceptione){}
}
}

Output:

sampledata..
FROMSERVER:SAMPLEDATA..

VAST Dept of Computer Science & Eng. (9)


Exp:3
BIDIRECTIONALCOMMUNICATIOUSINGTCP

Aim:

TowriteajavaprogramtoimplementthebidirectionalcommunicationbetweenclientandserverusingTCP

Algorithm:

Server:

Step1:Start
Step2:Createaclasbiserver
i.createanobjectforclassserverasobj2
ii.createthreadinobj2,t3,t4
iii.Runthethreadst3andt4
Step3:createaclassserverextendsthread
i.definethreadt3andt4
ii.deifnesocketcs
iii.defineserversocketss
iv.Definebufferedreaderbr3toreadinputfromkeyboardandbr4toreadfromclient
v.callthefunctionss.accept()toconnecttheclient
vi.ifcurrentprocessingthreadist3thendothesteps7tostep9
vii.s3=br3.readLine()
viii.Ds.writeBytes(s3)
ix.Ifs3='quit'thenexit
x.ifcurrentthreadist4thendostep11to13
xi.s4=br.readLine()
xii.Prints4
xiii.ifs4='quitthenexit
Step4:stop

Client:

Step1:Start
Step2:Createaclassbiclient
i.createanobjectforclassclient
ii.createthreadint1,t2
iii.Runthethreadst1andt2
Step3:createaclassclientextendsthread
i.definethreadt1andt2
ii.deifnesocketcs

VAST Dept of Computer Science & Eng. (10)


iii.Definebufferedreaderbr1toreadinputfromkeyboardandbr2toreadfromserver.
iv.definedataoutputstreamds
vi.ifthread=t1thendothesteps6tostep8
vii.s1=br1.readLine()
viii.ds.writeBytes(s1)
ix.Ifs1='quit'thenexit
x.ifthreadist2thendostep10to12
xi.s2=br2.readLine()
xii.Prints2
xiii.ifs2='quitthenexit
Step4:stop

Program:

biclient.java

importjava.io.*;
importjava.net.*;
classbiclient
{
publicstaticvoidmain(Stringargs[])throwsException
{
clientob1=newclient();
ob1.t1=newThread(ob1);
ob1.t2=newThread(ob1);
ob1.t1.start();
ob1.t2.start();
}
}
classclientextendsThread
{
Threadt1,t2;
Socketcs;
BufferedReaderbr1,br2;
DataOutputStreamds;
Strings1,s2;
client()
{
try
{
cs=newSocket("localhost",3000);
br1=newBufferedReader(newInputStreamReader(System.in));
ds=newDataOutputStream(cs.getOutputStream());
br2=newBufferedReader(newInputStreamReader(cs.getInputStream()));
}
catch(Exceptione){}
}
publicvoidrun()
{
if(Thread.currentThread()==t1)
{

VAST Dept of Computer Science & Eng. (11)


System.out.println("Sendmessagetoserver\n");
try
{ do
{ s1=br1.readLine();
ds.writeBytes(s1+'\n');
}
while(!s1.equals("quit"));
}
catch(Exceptione){}
}
if(Thread.currentThread()==t2)
{
try
{ do
{
s2=br2.readLine();
System.out.println("Messagefromserver:"+s2);
}
while(!s2.equals("quit"));
}
catch(Exceptione){}
}

}
}

biserver.java

importjava.io.*;
importjava.net.*;
classbiserver
{
publicstaticvoidmain(Stringargs[])throwsException
{
serverob2=newserver();
ob2.t3=newThread(ob2);
ob2.t4=newThread(ob2);
ob2.t3.start();
ob2.t4.start();
}
}
classserverextendsThread
{ Threadt3,t4;
Socketcs;
BufferedReaderbr3,br4;
DataOutputStreamds;
Strings3,s4;
ServerSocketss;
server()
{
try
{ br3=newBufferedReader(newInputStreamReader(System.in));
ss=newServerSocket(3000);
cs=ss.accept();
br4=newBufferedReader(newInputStreamReader(cs.getInputStream()));
ds=newDataOutputStream(cs.getOutputStream());

}
catch(Exceptione){}
}

VAST Dept of Computer Science & Eng. (12)


publicvoidrun()
{ if(Thread.currentThread()==t3)
{
System.out.println("Sendmessagetoclient\n");
try
{ do
{ s3=br3.readLine();
ds.writeBytes(s3+'\n');
}
while(!s3.equals("quit"));
}
catch(Exceptione){}
}
if(Thread.currentThread()==t4)
{ try
{ do
{ s4=br4.readLine();
System.out.println("Messagefromclient:"+s4);
if(s4.equals("quit"))
break;
}
while(!s4.equals("quit"));
}
catch(Exceptione){}
}
}
}

Output:

Sendmessagetoclient

messagefromclient:hai
messagefromclient:hai
messagefromclient:howareyou?
messagefromclient:Imgood,Whataboutu?
messagefromclient:Imfine,thankyou
messagefromclient:yah!

VAST Dept of Computer Science & Eng. (13)


Exp:4
BIDIRECTIONALCOMMUNICATIONUSINGUDP
Aim:

TowriteajavaprogramtoimplementthebidirectionalcommunicationusingUDP

Algorithm:

Server:

Step1:start
Step2:createadatagramsocketcalledserversocket
Step3:create2bytearrayreceivedataandsenddata
Step4:createadatagrampacketreceivepacket
Step5:receivepacketfromclient
Step6:getclientsentence!=byerepeatstep7to12
Step7:printclientstring
Step8:readinputandsenetencefromtheuser
Step9:getIPaddressandportnoofClient
Step10:storethesentencesenddata
Step11:createadatagrampacketusingsenddata
Step12:sendthepackettotheclient
Step13:stop

Client:

Step1:start
Step2:createadatagramsocketcalledclientsocket
Step3:getIPAddressofhost
Step4:Create2bytearraysenddataandreceivedata
Step5:rgetsentencefromuserandstoreinsenddata
Step6:createadatagrampacketsendpacketusingsenddata
Step7:createadatagrampacketreceivepacketandreadthepacketfromserver
Step8:readitheserversentencefromthereceivepacket
Step9:printtheserversentence
Step10:ifsentence='bye'thenexitelsedothestepfrom5to10
Step11:stop

Program:
udpc.java

importjava.io.*;
importjava.net.*;
classudpc
{
publicstaticDatagramSocketds1,ds2;
publicstaticDatagramPacketdp1,dp2;
publicstaticvoidmain(Stringargs[])throwsException
{
bytebuffer1[]=newbyte[1024];
bytebuffer2[]=newbyte[1024];
ds1=newDatagramSocket(10789);
ds2=newDatagramSocket(10792);
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("TwoWayCommunication");

VAST Dept of Computer Science & Eng. (14)


System.out.println("");
InetAddressid=InetAddress.getLocalHost();
while(true)
{
dp1=newDatagramPacket(buffer1,buffer1.length);
ds1.receive(dp1);
Stringstr=newString(dp1.getData(),0,dp1.getLength());
System.out.println(RecievedText:+str);
if((str==null)||(str.equals("end")))break;
System.out.println("EnterText:");
Stringstr2=br.readLine();
buffer2=str2.getBytes();
dp2=newDatagramPacket(buffer2,str2.length(),id,10791);
ds2.send(dp2);
if((str2==null)||(str2.equals("end")))break;

}}
}

udps.java

importjava.io.*;
importjava.net.*;
classudps
{
publicstaticDatagramSocketds1,ds2;
publicstaticDatagramPacketdp1,dp2;
publicstaticvoidmain(Stringargs[])throwsException
{
bytebuffer1[]=newbyte[1024];
bytebuffer2[]=newbyte[1024];
ds1=newDatagramSocket(10790);
ds2=newDatagramSocket(10791);
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("TwoWayCommunication");
System.out.println("");
InetAddressid=InetAddress.getLocalHost();
while(true)
{
System.out.println("EnterText");
Stringstr=br.readLine();
buffer1=str.getBytes();
dp1=newDatagramPacket(buffer1,str.length(),id,10789);

VAST Dept of Computer Science & Eng. (15)


ds1.send(dp1);
if((str==null)||(str.equals("end")))
break;
dp2=newDatagramPacket(buffer2,buffer2.length);
ds2.receive(dp2);
Stringstr4=newString(dp2.getData(),0,dp2.getLength());
System.out.println("Receivedtext"+str4);
if((str4==null)||(str4.equals("end")))
break;

Output:


TwowayCommunication

RecievedText:hai
EnterText:
hello
RecievedText:howru?
EnterText:
Fine..!
RecievedText:
end
EnterText:
end

VAST Dept of Computer Science & Eng. (16)


Exp:5
BROADCASTINGUSINGTCP
Aim

WriteaJavaprogramtoimplementBroadcastingusingTCP

Algorithm:

Server:

Step1:start
Step2:initializesocketarray
Step3:initializeaserversocket
Step4:create2threadstacceptandtsend
Step5:defineabufferedreaderbrtoreadinputfromkeyboard
Step6:defineadataoutputstreamdstosenddata
Step7:initializecount=0
Step8:runthethreadtacceptandtsend
Step9:ifcurrentprocessingthread=tacceptthendostep10to11
Step10:sock[count]=ss.accept
Step11:repeatstep10
Step12:ifcurrentprocessingthread=tsendthendosteps13to15
Step13:str=br.readLine()
Step14:sendthestringstrtoclients
Step15:ifstr='end'thenexit
Step16:Stop

Client:

Step1:Start
Step2:DefineaSocketcs
Step3:usebufferedReaderbrtoreadinputfromtheserver
Step4:str=br.readLine()
Step5:Printstr
Step6:ifstr='exit'thenexitelsedothestepfrom4to6
Step7:Stop

Program:

BroadClient.java

importjava.net.*;
importjava.io.*;
publicclassBroadClient
{
publicstaticvoidmain(Stringargs[])throwsException
{Socketcs=newSocket("localhost",5555);
Stringstr;
BufferedReaderbr=newBufferedReader(newInputStreamReader(cs.getInputStream()));
do
{ str=br.readLine();
System.out.println(str);
}
while(!str.equals("exit"));
}}

VAST Dept of Computer Science & Eng. (17)


BroadServer.java

importjava.io.*;
importjava.net.*;
publicclassBroadServerimplementsRunnable
{
Socketsock[]=newSocket[20];
ServerSocketss;
Threadtaccept,tsend;
BufferedReaderbr;
DataOutputStreamds;
intcount=0;
Stringstr;
BroadServer()
{ try
{ ss=newServerSocket(5555);
br=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Serverstarted");
}
catch(Exceptione){}
taccept=null;
tsend=null;
}
publicvoidrun()
{
if(Thread.currentThread()==taccept)
{do
{try{
sock[count]=ss.accept();
System.out.println("client"+count+"connected");
++count;
}
catch(Exceptione){}
}
while(true);
//System.exit(0);
}
elseif(Thread.currentThread()==tsend)
{ do
{try{
str=br.readLine();
for(inti=0;i<count;i++)

VAST Dept of Computer Science & Eng. (18)


{ds=new
DataOutputStream(sock[i].getOutputStream());
ds.writeBytes(str+'\n');
}
}
catch(Exceptione){}
}
while(!str.equals("Exit"));
}
}
publicstaticvoidmain(Stringargs[])
{ BroadServerbs=newBroadServer();
bs.taccept=newThread(bs);
bs.tsend=newThread(bs);
bs.taccept.start();
bs.tsend.start();
}
}

Output:

Connected
Serverstarted
client0:TheWorldatyourfingertips..!!!
Exit
client1:TheWorldatyourfingertips..!!!
Exit
client2:TheWorldatyourfingertips..!!!
Exit
client3:TheWorldatyourfingertips..!!!
Exit
client4:TheWorldatyourfingertips..!!!
Exit

VAST Dept of Computer Science & Eng. (19)


Exp:6
PUBLICCHAT

Aim:

WriteaJavaprogramtoimplementpublicchat(TCP).(amessageenteredinanyonesidewillbedisplayedtoall
otherhostsconnected)

Algorithm:

Server:
Step1:start
Step2:DefineServersocketsoc[30]
Step3:Definebufferdreaderbr3toreadstreamfromclient
Step4:thread=t
Step5:Createobjectforthissameclassobj
Step6:createonethreadtacceptandrunit
Step7:initializecount=0
Step8:soc[count]=ss.accept
Step9:t[accept]createasathread.
Step10:runthethreadt[count]
Step11:count++
Step12:repeatthestep8to11
Step13:initializei=0
Step14:ifI<countdostep15tostep22
Step15:ifcurrentthread=t[i]thendothestep16tostep21
Step16:str=br3.readLine()
Step17:initializej=0
Step18:ifj<countdostep19and21
Step19:ds=senddtattosoc[i]
Step20:ds.writeBytes(str)
Step21:j++
Step22:i++
Step23:ifstr!=quitthengoto14
Step24:Stop

Client
Step1:Start
Step2:Createaclasspcclient
Step3:definebufferedreaderbr1toreadinputfromkeyboardbr2toreadfromserver
Step4:Definedstosenddataintoserver
Step5:Create2threadst1andt2intoserver
Step6:Ifcurrentthreadt1andt2thenrunit
Step7:ifcurrentthreadist1thendostep7tostep8
Step8:s1=br1.readLine()
Step9:ifcurrentThread=t1
Step10:s2=br2.readLine()
Step11:PrinttheStrings2
Step12:Stop

Program:
Server:
importjava.io.*;
importjava.net.*;
classpcserverimplementsRunnable
{ Socketsoc[]=newSocket[20];
ServerSocketss;
Stringstr;
Threadtaccept;

VAST Dept of Computer Science & Eng. (20)


BufferedReaderbr3;
DataOutputStreamds;
intcount=0;
Threadt[]=newThread[20];
pcserver()
{ try
{ ss=newServerSocket(1600);
System.out.println("Serverstarted");
}catch(Exceptione){}
}
publicvoidrun()
{
if(Thread.currentThread()==taccept)
{ do
{try
{ soc[count]=ss.accept();
t[count]=newThread(this);
System.out.println("client"+count+"connected");
t[count].start();
++count;
}
catch(Exceptione){}
}
while(true);
}
else
{ for(inti=0;i<count;i++)
{if(Thread.currentThread()==t[i])
{try
{do
{
br3=newBufferedReader(newInputStreamReader(soc[i].getInputStream()));
str=br3.readLine();
for(intj=0;j<count;j++)
{
if(i!=j)
{
ds=newDataOutputStream(soc[j].getOutputStream());
ds.writeBytes("client"+i+"says:"+str+'\n');
}
}
}while(!str.equals("quit"));
}
catch(Exceptione){}
}
}
}
}
publicstaticvoidmain(Stringargs[])
{pcserverobj=newpcserver();
obj.taccept=newThread(obj);
obj.taccept.start();
}
}

Client:
importjava.io.*;
importjava.net.*;
publicclasspcclientimplementsRunnable
{

VAST Dept of Computer Science & Eng. (21)


Socketsock;
Threadt1,t2;
BufferedReaderbr1,br2;
DataOutputStreamds;Strings1,s2;
pcclient()
{ try
{sock=newSocket("localhost",1600);
br1=newBufferedReader(newInputStreamReader(System.in));
br2=newBufferedReader(newInputStreamReader(sock.getInputStream()));
ds=newDataOutputStream(sock.getOutputStream());
System.out.println("Clientstarted\n");
}catch(Exceptione){}
}
publicvoidrun()
{ if(Thread.currentThread()==t1)
{do
{try { s1=br1.readLine();
ds.writeBytes(s1+'\n');
}
catch(Exceptione){}
}while(!s1.equals("quit"));
}
elseif(Thread.currentThread()==t2)
{ do {
try {s2=br2.readLine();
System.out.println(s2);
}
catch(Exceptione){}
}while(!s2.equals("quit"));

}
}
publicstaticvoidmain(Stringargs[])
{pcclientobj=newpcclient();
obj.t1=newThread(obj);
obj.t2=newThread(obj);
obj.t1.start();
obj.t2.start();
}
}

Output:
Clientstarted
Client0says:hi
Client1says:hi
Client2says:hi
Client3says:hi
Client4says:hi
Client0says:quit
Client1says:quit
Client2says:quit
Client3says:quit
Client4says:quit

VAST Dept of Computer Science & Eng. (22)


Exp:7
FILETRANSFERPROTOCOL
Aim:

WriteaJavaprogramtotransferfilebetweenclieneandserverusingFTP

Algorithm:

Server:

Step1:Start
Step2:InitializeServerSocketss1andss2
Step3:DefineBufferdreaderbr1toreadstringfromclient
Step4:name=br1.readLine()
Step5:Connectsocket=ss2throughsockets2
Step6:index=name.Substring(index+1)
Step7:method=name.Substring(0,index)
Step8:fname=name.Substring(index+1)
Step9:Createaafilefpwithnameframe
Step10:ifmethod=getthendothestep11tostep15
Step11:Defineaprintwriterpw1
Step12:Definefileinputstreamf
Step13:j=f.read
Step14:pw1.println((char)*s)
Step15:while(j!=1)
Step16:ifmethod=putthendostep17tostep24
Step17:Deifnebr2asbufferdreadedtoreadinputformclient
Step18:Definef0asfileinputstream
Step19:h=br2.readLine()
Step20:b=h.getBytes()
Step21:Printh
Step22:ifh!=nulldoSteps19to23
Step23:Stop

Client

Step1:Start
Step2:InitializepacketSocket
Step3:Definepw1asprintWriter
Step4:Deifinebr1toreadInputfromkeyboard
Step5:name=br1.readLine()
Step6:pw1.Println(name)
Step7:index=name.indexof()
Step8:fname=name.Substring(index+1)
Step9:Method=name.SubString(0,index)
Step10:printfname
Step11:Defineasocket2assocket
Step12:definepw2asprintwriter
Step13:Createaanewfilefwithfilename'fname
Step14:ifmethod='get'thendosteps15to17
Step15:definebrasbufferdreadertoreadl=inputfromserver
Step16:fsdefineasfileoutputstream
Step17:b=br2.readLine()
Step18:buf=h.getBytes()
Step19:f.write(buf)
Step20:whileh!=NULLthendostep17to20
Step21:ifmethod=putthendostep22to25
Step22:definefpasfileinputstream

VAST Dept of Computer Science & Eng. (23)


Step23:r=fp.read()
Step24:printr
Step25:pw2.print(r)
Step26:whiler!=10dostep23to26
Step27:Stop

Program:
ftpclient.java

importjava.io.*;
importjava.net.*;
publicclassftpclient
{
publicstaticvoidmain(Stringargs[])throwsException
{try{
intr,index;
Stringh,fname,method,name;
Socketsock1=newSocket("localhost",10000);
PrintWriterpw1=newPrintWriter(sock1.getOutputStream(),true);
BufferedReaderbr1=newBufferedReader(newInputStreamReader(System.in));
System.out.println("..ftpclient...\nEnterthecommand:get[file]/put[file]");
name=br1.readLine();
pw1.println(name);
index=name.indexOf("");
fname=name.substring(index+1);
method=name.substring(0,index);
System.out.println(fname);
Socketsock2=newSocket("localhost",10001);
PrintWriterpw2=newPrintWriter(sock2.getOutputStream(),true);
Filef=newFile(fname);
System.out.println(":.."+method+".."+fname+"..");
if(method.equals("get"))
{
BufferedReaderbr2=newBufferedReader(newInputStreamReader(sock2.getInputStream()));
bytebuf[]=newbyte[1024];
FileOutputStreamfs=newFileOutputStream(f);
do{ h=br2.readLine();
buf=h.getBytes();
fs.write(buf);
}while(!h.equals(null));
System.out.println("filereceived"+fname);
}
else
{
FileInputStreamfp=newFileInputStream(f);
do{r=fp.read();
System.out.println(r);
pw2.println((char)r);
}while(r!=10);
System.out.println("filesentsuccussfully"+fname);
}}catch(Exceptione){}
}
}

ftpserver.java

importjava.io.*;
importjava.net.*;
publicclassftpserver

VAST Dept of Computer Science & Eng. (24)


{
publicstaticvoidmain(Stringargs[])throwsException
{
t ry { intj,index;
Stringh,fname,method,name;
ServerSocketss1=newServerSocket(10000);
ServerSocketss2=newServerSocket(10001);
Sockets1=ss1.accept();
BufferedReaderbr1=newBufferedReader(new
InputStreamReader(s1.getInputStream()));
name=br1.readLine();
Sockets2=ss2.accept();
index=name.indexOf("");
fname=name.substring(index+1);
method=name.substring(0,index);
Filefp=newFile(fname);
System.out.println(":"+method+"file"+fname+"...");
if(method.equals("get"))
{
PrintWriterpw1=newPrintWriter(s2.getOutputStream(),true);
FileInputStreamf=newFileInputStream(fp);
do
{j=f.read();
pw1.println((char)j);
}while(j!=1);
}
elseif(method.equals("put"))
{
BufferedReaderbr2=newBufferedReader(new
InputStreamReader(s2.getInputStream()));
byteb[]=newbyte[1024];
FileOutputStreamfo=newFileOutputStream(fp);
System.out.println("..transfer..."+fname+"..");
do
{h=br2.readLine();
b=h.getBytes();
System.out.println(h);
fo.write(b);
}while(!h.equals(null));
}
}catch(Exceptione){}
}
}

Output:

Serverside:

:getfiley.txt...
:putfilex.txt...
..transfer....x.text..

Clientside:
Enterthecommand:get|file|/put|file|
gety.txt
y.txt
...get..y.txt..
ftpclient

VAST Dept of Computer Science & Eng. (25)


Stop&WaitProtocol
stop-n-wait" (sometimes known as "positive acknowledgement with retransmission") is the fundamental technique to provide
reliable transfer under unreliable packet delivery system.After transmitting one packet, the sender waits for an
acknowledgment (ACK) from the receiver before transmitting the next one. In this way, the sender can recognize that the
previous packet is transmitted successfuly and we could say "stop-n-wait" guarantees reliable transfer between nodes.To
support this feature, the sender keeps a record of each packet it sends.Also, to avoid confusion caused by delayed or
duplicated ACKs, "stop-n-wait" sends each packets with unique sequence numbers and receives that numbers in each ACKs

GoBackNProtocol

GoBackNARQisaspecificinstanceoftheautomaticrepeatrequest(ARQ)protocol,inwhichthe
sendingprocesscontinuestosendanumberofframesspecifiedbyawindowsizeevenwithoutreceivingan
acknowledgement(ACK)packetfromthereceiver.Itisaspecialcaseofthegeneralslidingwindowprotocolwith
thetransmitwindowsizeofNandreceivewindowsizeof1.

Thereceiverprocesskeepstrackofthesequencenumberofthenextframeitexpectstoreceive,andsends
thatnumberwitheveryACKitsends.Thereceiverwilldiscardanyframethatdoesnothavetheexactsequence
numberitexpects(eitheraduplicateframeitalreadyacknowledged,oranoutoforderframeitexpectstoreceive
later)andwillresendanACKforthelastcorrectinorderframe.Oncethesenderhassentalloftheframesinits
window,itwilldetectthatalloftheframessincethefirstlostframeareoutstanding,andwillgobacktosequence
numberofthelastACKitreceivedfromthereceiverprocessandfillitswindowstartingwiththatframeand
continuetheprocessoveragain.

GoBackNARQisamoreefficientuseofaconnectionthanStopandwaitARQ,sinceunlikewaitingfor
anacknowledgementforeachpacket,theconnectionisstillbeingutilizedaspacketsarebeingsent.Inother
words,duringthetimethatwouldotherwisebespentwaiting,morepacketsarebeingsent.However,thismethod
alsoresultsinsendingframesmultipletimesifanyframewaslostordamaged,ortheACKacknowledgingthem
waslostordamaged,thenthatframeandallfollowingframesinthewindow(eveniftheywerereceivedwithout
error)willberesent.Toavoidthis,SelectiveRepeatARQcanbeused.

FingerUtility
TheName/Fingerprotocol,writtenbyDavidZimmerman,isbasedonRequestforcomments
documentRFC742(December1977)asaninterfacetothename[clarificationneeded]andfingerprogramsthat
providestatusreportsonaparticularcomputersystemoraparticularpersonatnetworksites.Thefingerprogram
waswrittenin1971byLesEarnestwhocreatedtheprogramtosolvetheneedofuserswhowantedinformation
onotherusersofthenetwork.Informationonwhoisloggedinwasusefultochecktheavailabilityofapersonto
meet.Thiswasprobablytheearliestformofpresenceinformationforremotenetworkusers.

VAST Dept of Computer Science & Eng. (26)


Priortothefingerprogram,theonlywaytogetthisinformationwaswithawhoprogramthatshowedIDs
andterminallinenumbers(theserver'sinternalnumberofthecommunicationline,overwhichtheuser'sterminal
isconnected)forloggedinusers.Earnestnamedhisprogramaftertheideathatpeoplewouldruntheirfingers
downthewholisttofindwhattheywerelookingfor.

CommonGatewayInterface

Thecommongatewayinterface(CGI)isastandardwayforaWebservertopassaWebuser's
requesttoanapplicationprogramandtoreceivedatabacktoforwardtotheuser.WhentheuserrequestsaWeb
page(forexample,byclickingonahighlightedwordorenteringaWebsiteaddress),theserversendsbackthe
requestedpage.However,whenauserfillsoutaformonaWebpageandsendsitin,itusuallyneedstobe
processedbyanapplicationprogram.TheWebservertypicallypassestheforminformationtoasmallapplication
programthatprocessesthedataandmaysendbackaconfirmationmessage.Thismethodorconventionfor
passingdatabackandforthbetweentheserverandtheapplicationiscalledthecommongatewayinterface(CGI).
ItispartoftheWeb'sHypertextTransferProtocol(HTTP).

Thecommongatewayinterfaceprovidesaconsistentwayfordatatobepassedfromtheuser'srequestto
theapplicationprogramandbacktotheuser.Thismeansthatthepersonwhowritestheapplicationprogramcan
makessureitgetsusednomatterwhichoperatingsystemtheserveruses(PC,Macintosh,UNIX,OS/390,or
others).It'ssimplyabasicwayforinformationtobepassedfromtheWebserveraboutyourrequesttothe
applicationprogramandbackagain.

VAST Dept of Computer Science & Eng. (27)


Exp:8
STOPANDWAITPROTOCOL

Aim
:

Writeajavaprogramtoimplementstopandwaitprotocol

Algorithm:

server:

Step1:Start
Step2:Declarepackagejava.ioandjava.net
Step3:DeclareclassvariablesssforServerScokets.Sfotsocket,brforbufferedreader,pwforprintwrite,t1,t2
forthread,
count,twostringsstrsndandstrrcv
Step4:Declareconstructorwhereserverstartsatport7071andwaitsforclient
Step5:Declarefunctionwindowprocess
i.dostepsiitovwhiletrue
ii.readthedatatosendinstrrcv
iii.readthecountvariable
iv.Ifstrrcvequals'data'printcount1andsenddata
v.ifexceptionprinterror
Step6:Inmainfunctiondeclareobjectforstopwaitserverandcallthefunctionwindowprocess.
Step7:Srop

Client:

Step1:start
Step2:Declarepackagejava.netandjava.io
Step3:DeclarevariablesforsocketbrforBufferedReader,pwforprintwriter,t1,t2forthread,upandlow,count
windowfor
integer,stringstrsndandstrrcv
Step4:Declareintheconstructorsocketconnectionathost'127.0.01'andport7071andstaetwothreadst1and
t2
Step5:DeclareFunction
i.ifthreadist1thendothesteps6toiitovwhiletrue
ii.up++
iii.Printwaitingforserverwhile(uplow>windowprocess)
ivprintsendingdata
v.printstrsndandcount
vi.Elseifrepeatstepviiandviiiwhiletrue
vii.Readdatainstrrcv
viii.Ifstrrcvequal'Ack'thenprint'receivedanddecremnetlow++
Step6:inmainfunctiondeclareanobjectforclient

Program:

StopwaitClient.java

importjava.io.*;
importjava.net.*;
publicclassStopwaitClientimplementsRunnable
{
Sockets;
BufferedReaderbr;
PrintWriterpw;
Threadt1,t2;
intup=0,low=0,count=0,window=1;

VAST Dept of Computer Science & Eng. (28)


StringstrSnd=newString("DATA");
StringstrRcv=newString();
StopwaitClient()
{ try {
s=newSocket("127.0.0.1",7071);
System.out.println("\nClientstarted...");
br=newBufferedReader(newInputStreamReader(s.getInputStream()));
pw=newPrintWriter(s.getOutputStream(),true);
t1=newThread(this,"t1");
t2=newThread(this,"t2");
t1.start();
t2.start();
}
catch(Exceptione)
{ System.out.println(e); }
}
publicvoidrun()
{ try {
if(Thread.currentThread()==t1)
{ while(true)
{ up++;
while(uplow>window)
{System.out.println("\nSenderwaitingforacknowledgement\n");
t1.sleep(1000);
}
System.out.println("\nSendingDATA"+(up1));
pw.println(strSnd);
count=up;
pw.println(count);
}
}
else
{ while(true)
{ strRcv=br.readLine();
if(strRcv.equals("ACK"))
{
System.out.println("\nAcknowledgementreceivedforDATA"+low);
low++;t2.sleep(1000);
} }
} }
catch(Exceptione)
{ System.out.println(e); }
}
publicstaticvoidmain(String[]arg)
{ newStopwaitClient(); }
}

StopwaitServer.java

importjava.io.*;
importjava.net.*;
publicclassStopwaitServer
{
ServerSocketss;
Sockets;
BufferedReaderbr;
PrintWriterpw;
Threadt1,t2;
intcount=0;
StringstrSnd=newString("ACK");

VAST Dept of Computer Science & Eng. (29)


StringstrRcv=newString();
StopwaitServer()
{
try
{
ss=newServerSocket(7071);
System.out.println("\nServerstarted...");
s=ss.accept();
System.out.println("\nClientconnected");
br=newBufferedReader(newInputStreamReader(s.getInputStream()));
pw=newPrintWriter(s.getOutputStream(),true);

}
catch(Exceptione)
{ System.out.println(e); }
}
publicvoidwindowProcess()
{ try {
while(true)
{ strRcv=br.readLine();
System.out.println("\n\nTEST"+strRcv);
count=Integer.parseInt(br.readLine());
if(strRcv.equals("DATA"))
{
System.out.println("ReceivedDATA"+(count1));
pw.println(strSnd);
System.out.println("AcknowledgedforDATA"+(count1)+"sent");
} }
}
catch(Exceptione)
{ System.out.println(e); }

}
publicstaticvoidmain(String[]arg)
{ StopwaitServerserv=newStopwaitServer();
serv.windowProcess();
}
}

Output:

Serverside:

ServerStarted..
Clientconnected

TESTDATA
ReceivedDATA0
AcknowledgedforDATA0sent

TESTDATA
ReceivedDATA1
AcknowledgedforDATA0sent

TESTDATA

VAST Dept of Computer Science & Eng. (30)


ReceivedDATA2
AcknowledgedforDATA0sent

TESTDATA
ReceivedDATA3
AcknowledgedforDATA0sent

TESTDATA
ReceivedDATA4
AcknowledgedforDATA0sent

ClientSide:

ClientStarted...
SendingDATA0
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0

SendingDATA1
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0

SendingDATA2
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0

SendingDATA3
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0

SendingDATA4
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0

VAST Dept of Computer Science & Eng. (31)


Exp:9
GOBACKNPROTOCOL
Aim:

WriteaJavaProgramtoimplementGoBackNProtocol

Algorithm:

ServerSide

Step1:Start

Step2:Declarepackagesioand.net

Step3:Declarevariablesssforserversocketsforsocket,brforBufferedReader,pwforPrintWriterdatacount,
ackcount,temp,ack
prev,countandstringvariablesStrSnd,StrRcv

Step4:Declareaconstructorwithserverstartsatportnumber8282

Step5:Printserverstarted

Step6:Ifclientconnectedthenprintclientconnected

Step7:DeclarewindowProcess()function

Step7a:Dostepsitoviwhiletrue
i.ReadinputinStrRcvandcountdataindatacount

ii.IfStrRcv=DATAthendosteps7d7e
iii.Decrementtempby1
iv.Iftemp=0displaydatacorrupted,printmsgSndanddatacountandtemp=6
v.Elseackcount=ackRevCount+1

vi.If(datacount=ackcount)dislpaydatarecievedandprintStrSndanddatacountelseprintdata
discarded

Step8:Startmain()anddeclareanobjectserverandcallfunctionwindowprocess

Step9:Stop

ClientSide:

Step1:Start

Step2:Declarejavapackages

Step3:Declarevariables

Step4:Declareconstructorwheresocketconnectionat"127.0.0.1"8282portanddeclareclientstarted.Start
threadt1andt2

Step5:Declarerun()

Step5a:Ifthread!=t1thendostepsitoii

i.PrintStrSndanddatacount
ii.Printsenddata
iii.Incrementdatacountby1

VAST Dept of Computer Science & Eng. (32)


iv.t1.sleep(1000)
v.Elsedostepsvitoix
vi.ReadinputtoStrRcv
vii.IfStrRcvisAckprintAckreceived
viii.ElseifStrRcvequalsNprintsendingagain
ix.datacount=ackcount
Step6:Startmain()withobjectGBNClient
Step7:Stop
Program:
GBNClient.java

importjava.io.*;
importjava.net.*;
publicclassGBNClientimplementsRunnable
{
Sockets;
BufferedReaderbr;
PrintWriterpw;
Threadt1,t2;
intdataCount=0,ackCount=0;
StringstrSnd=newString("data");
StringstrRcv=newString();
privatefinaljava.util.concurrent.Semaphores1=newjava.util.concurrent.Semaphore(1);

GBNClient()
{ try
{ s=newSocket("127.0.0.1",8282);
System.out.println("\nClientstarted");
br=newBufferedReader(newInputStreamReader(s.getInputStream()));
pw=newPrintWriter(s.getOutputStream(),true);
t1=newThread(this,"t1");
t2=newThread(this,"t2");
t1.start();
t2.start();
t1.join();
t2.join();
}
catch(Exceptione)
{ System.out.println(e); }
}
publicvoidrun()
{ try
{ if(Thread.currentThread()==t1)
{ while(true)
{ pw.println(strSnd);
pw.println(dataCount);
System.out.println("\nsenddata"+dataCount);
//s1.acquire();
dataCount++;

VAST Dept of Computer Science & Eng. (33)


//s1.release();
t1.sleep(1000);
}
}
else
{ while(true)
{ strRcv=br.readLine();
ackCount=Integer.parseInt(br.readLine());
if(strRcv.equals("ack"))
{ System.out.println("\nACKreceivedfordata"+ackCount);
t2.sleep(2000);
}
elseif(strRcv.equals("na"))
{ System.out.println("\nSendingagain");
t2.sleep(2000);
//s1.acquire();
dataCount=ackCount;
//s1.release();
} }
}}
catch(Exceptione)
{System.out.println(e);}
}
publicstaticvoidmain(String[]arg)
{ newGBNClient(); }
}

GBNServer.java

importjava.io.*;
importjava.net.*;
publicclassGBNServer
{
ServerSocketss;
Sockets;
BufferedReaderbr;
PrintWriterpw;
intdataCount=0,ackCount=0,temp=3,ackPrevCount=1;
StringstrSnd=newString("ack");
StringnegStrSnd=newString("na");
StringstrRcv=newString();
GBNServer()
{
try
{ ss=newServerSocket(8282);
System.out.println("\nServerstarted");
s=ss.accept();

VAST Dept of Computer Science & Eng. (34)


System.out.println("\nClientconnected");
br=newBufferedReader(newInputStreamReader(s.getInputStream()));
pw=newPrintWriter(s.getOutputStream(),true);
}
catch(Exceptione)
{ System.out.println(e); }
}
publicvoidwindowProcess()
{ try {while(true)
{ strRcv=br.readLine();
dataCount=Integer.parseInt(br.readLine());
if(strRcv.equals("data"))
{ temp;
if(temp==0)
{ System.out.println("\nDataCorrupted"+dataCount);
pw.println(negStrSnd);
pw.println(dataCount);
temp=6;
}
else
{ ackCount=ackPrevCount+1;
if(dataCount==ackCount)
{ System.out.println("\nDataRecieved"+dataCount);
pw.println(strSnd);
pw.println(dataCount);
System.out.println("Acknowledged"+dataCount);
ackPrevCount=dataCount;
}
else
{System.out.println("\nDataDiscarded");}
}
}
}
}
catch(Exceptione)
{ System.out.println(e); }
}
publicstaticvoidmain(String[]arg)
{
GBNServerserv=newGBNServer();
serv.windowProcess();
}
}

Output:

ServerSide:
Serverstarted...
ClientConnected
DataRecieved0
Acknowledged0
DataRecieved1
Acknowledged1
DataCorrupted2

VAST Dept of Computer Science & Eng. (35)


DataDiscarded
DataDiscarded
DataDiscarded
DataDiscarded
DataRecieved2
Acknowledged2
DataCorrupted3
DataDiscarded
DataDiscarded
DataRecieved3
Acknowledged3
DataRecieved4
Acknowledged4
DataRecieved5
Acknowledged5
ClientSide:
ClientStarted
SendDATA0
Acknowledgementrecievedfordata0
SendDATA1
SendDATA2
Acknowledgementrecievedfordata1
SendDATA3
SendDATA4
Sendingagain
SendDATA5
SendDATA6
SendDATA2
Acknowledgementrecievedfordata2
SendDATA3
Sendingagain
SendDATA4
SendDATA5
SendDATA3
Acknowledgementrecievedfordata3
SendDATA4
SendDATA5
Acknowledgementrecievedfordata4

VAST Dept of Computer Science & Eng. (36)


Exp:10
FINGERUTILITYPROTOCOL

Aim

WriteaJavaprogramtoimplementFingerUtility

Algorithm:

Step1:Start

Step2:DeclareTCP_Finger_ClientClass

Step3:Inmain()dosteps4to7

Step4:Ifargslength!=1printinvalidno:ofparameters

Step5:Otherwiseifargs[0].indexof("@")=1printinvalidparameter

Step6:Otherwisegettheusernameusingsubstring

Step7:Createconnectiontoserverusingsocketobjects

Step8:DefinePrintStreamobjectoutandDataInputStreamobjectin

Step9:Writeusernametosocketoutput

Step10:Readresponsefromsocketusingintoline

Step11:While(line!=NULL)printlineandreadnextline

Step12:Closeconnection

Step13:Stop

Program:

TCP_Finger_Client.java

importjava.io.*;
importjava.net.*;

publicclassTCP_Finger_Client
{
publicstaticvoidmain(Stringargs[])
{
//Checkcommandlineparamaters
if(args.length!=1)
{
System.err.println("Invalidnumberofparamaters");
System.exit(1);
}
else
//Checkforexistenceof@inparamater
if(args[0].indexOf("@")==1)
{
System.err.println("Invalidparamater:syntaxuser@host");
System.exit(1);

VAST Dept of Computer Science & Eng. (37)


}

//Splitcommandlineparamateratthe@character
Stringusername=args[0].substring(0,args[0].indexOf("@"));
Stringhostname=args[0].substring(args[0].indexOf("@")+1,args[0].length());

try
{
System.out.println("Connectingto"+hostname);

//Createaconnectiontoserver
Sockets=newSocket(hostname,80);

//Createinputandoutputstreamstosocket
PrintStreamout=newPrintStream(s.getOutputStream());
DataInputStreamin=newDataInputStream(s.getInputStream());

//Writeusernametosocketoutput
out.println(username);

//Readresponsefromsocket
Stringline=in.readLine();

while(line!=null)
{
System.out.println(line);

//Readnextline
line=in.readLine();
}

//Terminateconnection
s.close();

}
catch(SocketExceptione)
{
System.err.println("Socketerror:"+e);
}
catch(UnknownHostExceptione)
{
System.err.println("Invalidhost!");
}
catch(IOExceptione)
{
System.err.println("I/Oerror:"+e);
}
}

Output:

JavaTCP_Finger_Clientstudent@administratordesktop

Connectingtoadministratordesktop

<!DOCTYPEHTMLPUBLIC"//IETF//DTDHTML2.0//EN">

VAST Dept of Computer Science & Eng. (38)


<html><head>

<title>501MethodNotImplemented</title>

</head><body>

<h1>MethodNotImplemented</h1>

<p>studentto/notsupported<br/>

</p>

<hr>

<address>Apache/2.2.14(Ubuntu)Serverat127.0.1.1Port80</address>

</body></html>

VAST Dept of Computer Science & Eng. (39)


Exp:11
COMMONGATEWAYINTERFACE
Aim:

Towriteaprogramfordisplayingthedetailsextractedfromregistrationform

Algorithm:

Step1:Start

Step2:Createhtmlfileforregistrationform

Step3:Includenecessarydetailsinit

Step4:Submitthespecifiedformintoreg.cgibyusingPOSTmethod

Step5:Inreg.cgifileextractthedetailsfrommy.html

Step6:Displaymessage"Yourregistrationwassuccessful"andshowdetails

Step7:Stop

my.html

<html>
<head><title>RegistartionForm</title></head>
<body>
<h1>ENTERDETAILS</h1>
<formaction="./cgibin/reg.cgi"method="post"><table>
<tr>
<td>FirstName</td>
<td><inputtype="text"name="fname"/></td>
</tr>
<tr>
<td>LastName</td>
<td><inputtype="text"name="lname"/></td>
</tr>
<tr>
<td>Address</td>
<td><textareaname="address"></textarea></td>
</tr>
<tr>
<td>UserName</td>
<td><inputtype="text"name="uname"/></td>
</tr>
<tr>
<td>Password</td>
<td><inputtype="password"name="password"/></td>
</tr>
<tr>
<td>Sex</td>
<td><label>
<inputname="sex"type="radio"value="male"checked="checked"/>Male<br/>
</label>
<label>
<inputname="sex"type="radio"value="female"/>Female<br/>

VAST Dept of Computer Science & Eng. (40)


</label></td>
</tr>
<tr>
<td>Nationality</td>
<td><inputtype="text"name="nationality"/></td>
</tr>
<tr>
<td>EmailId</td>
<td><inputtype="text"name="email"/></td>
</tr>
<tr>
<td>Phoneno</td>
<td><inputtype="text"maxlength="10"name="phno"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><inputname="submit"type="submit"id="Submit1"value="Submit"/>
<inputid="Reset1"type="reset"value="Reset"/></td>
</tr>
</table>
</form>
</body>
</html>

reg.cgi

#!/usr/bin/perlw

useCGI":standard";

printheader;

printstart_html("CGIPerlform,usingCGI.pm");

my($fname,$lname,$address,$uname,$password,$sex,$nationality,$email,

$phno)=(param("fname"),param("lname"),param("address"),param("uname"),param("password"),param("sex"),pa

ram("nationality"),param("email"),param("phno"));

print"<b>$fname$lname</b>\n";

printh3("Yourregistrationwassuccessfullycompleted."),"\n";

printh4("Details:"),"\n";

print"<b>FirstName:</b>$fname<br/>\n";

print"<b>LastName:</b>$lname<br/>\n";

print"<b>Address:</b>$address<br/>\n";

print"<b>Nationality:</b>$nationality<br/>\n";

print"<b>Emailid:</b>$email<br/>\n";

print"<b>Phoneno:</b>$phno<br/>\n";

printend_html;

VAST Dept of Computer Science & Eng. (41)


Output:

VAST Dept of Computer Science & Eng. (42)


ADVANCEDEXPERIMENTS
**********

Exp:12

DATESERVERANDCLIENT
Aim:
WriteaJavaprogramtoimplementAtrivialdateserverandclientonewaycommunication.

Algorithm:

ServerSide

Step1:Start
Step2:Declarepackagesio,.net,.util
Step3:Declarevariables
Step4:createServerSockets=newServerSocket()
Step5:dosteps6to11while(true
Step6:print"WaitingForConnection..."
Step7:AssignSocketsoc=s.accept()
Step8:Createnewobjectout
Step9:print"ServerDate:"withfunctionDate();
Step10:out.close();
Step11:closethesoc:soc.close();
Step12:Stop

ClientSide

Step1:Start
Step2:Declarepackagesio,.net,
Step3:Declarevariables
Step4;createnewobjectsoc
Step5:createnewbufferedreaderobjectin
Step6:printin.readLine()
Step7:Stop

Program:
DateServer.java
//DateServer

importjava.net.*;
importjava.io.*;
importjava.util.*;

VAST Dept of Computer Science & Eng. (43)


classDateServer
{
publicstaticvoidmain(Stringargs[])throwsException
{
ServerSockets=newServerSocket(5217);

while(true)
{
System.out.println("WaitingForConnection...");
Socketsoc=s.accept();
DataOutputStreamout=newDataOutputStream(soc.getOutputStream());
out.writeBytes("ServerDate:"+(newDate()).toString()+"\n");
out.close();
soc.close();
}

}
}
Theclient
DateClient.java

importjava.io.*;
importjava.net.*;

classDateClient
{
publicstaticvoidmain(Stringargs[])throwsException
{
Socketsoc=newSocket(InetAddress.getLocalHost(),5217);
BufferedReaderin=newBufferedReader(
newInputStreamReader(
soc.getInputStream()
)
);

System.out.println(in.readLine());
}
}

Output:

administrator@adminSystemsLab:~$javacDateServer.java
administrator@adminSystemsLab:~$javaDateServer
WaitingForConnection...
WaitingForConnection...

administrator@adminSystemsLab:~$javacDateClient.java
administrator@adminSystemsLab:~$javaDateClient
ServerDate:WedNov0614:24:49IST2013

VAST Dept of Computer Science & Eng. (44)


Exp:13

SLIDINGWINDOWPROTOCOLS
Aim:

WriteaJavaProgramtoperformslidingwindowprotocols

Algorithm:

Step1:Starttheprogram.
Step2:Importpackages
Step3:createnewsocketofServerSocket():ser
Step4:Assigns=ser.accept()
Step5:setin=newDataInputStream(System.in)
Step6:setin1=newDataInputStream(s.getInputStream())
Step7:Assignsbuff[]asnewString[8]
Step8:PrintStreamp
Step9:declaresptr=0,sws=8,nf,anoandiasintegerandchasString
Step10:doStep11towhilethecondition'ch.equals("yes")'istrue
Step11:p=newPrintStream(s.getOutputStream())
Step12:print"Entertheno.offrames:"andreadasnf
Step13:p.println(nf)
Step14:ifnf<=sws1istruedostep15elsegotostep24
Step15:Print"Enter"+nf+"Messagestobesend
Step16:seti=1anddosteps17to20ifconditioni<=nfistrue {
Step17:buff[sptr]=in.readLine()
Step18:p.println(sbuff[sptr])
Step19:sptr=++sptr%8
Step20:i++
Step21:sws=nfandprint"Acknowledgmentreceived"
Step22: readano,andprint"for"+ano+"frames"
Step23:sws+=nf
Step24:println"Theno.offramesexceedswindowsize"andbreak
Step25:print"Doyouwantstosendsomemoreframes:"andreadch
Step26:p.println(ch)
Step27:closethesockets
Step28:stop
Receiver

Step1:Starttheprogram.
Step2:Importpackages
Step3:createnewobjectofServerSocket():ser

VAST Dept of Computer Science & Eng. (45)


Step4:createnewsockets
Step5:createnewobjofDataInputStream():in
Step6:createp=newPrintStream()
Step7:declarei=0,rptr=1,nf,rws=8asintegerrbuf[],chasString
Step8:dosteps9towhilethecondition(ch.equals("yes")istrue
Step9:readnf
Step10:iftheconditionnf<=rws1istruedothesteps11t016elsegoto17
Step11: i=1ifi<=nistruerepeatthesteps12to14untillconditionbreak,
Step12:rptr=++rptr%8andrbuf[rptr]=in.readLine()
Step13:println"ThereceivedFrame"+rptr+"is:"+rbuf[rptr]
Step14:i++
Step15:rws=nf;andprintlnAcknowledgmentsent"
Step16:p.println(rptr+1);andrws+=nf
Step17: break;
Step18:ch=in.readLine()
Step19:Stop

Program:

importjava.net.*;
importjava.io.*;
importjava.rmi.*;
publicclassslidsender
{
publicstaticvoidmain(Stringa[])throwsException
{
ServerSocketser=newServerSocket(10);
Sockets=ser.accept();
DataInputStreamin=newDataInputStream(System.in);
DataInputStreamin1=newDataInputStream(s.getInputStream());
Stringsbuff[]=newString[8];
PrintStreamp;
intsptr=0,sws=8,nf,ano,i;
Stringch;
do
{
p=newPrintStream(s.getOutputStream());
System.out.print("Entertheno.offrames:");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws1)
{System.out.println("Enter"+nf+"Messagestobesend\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws=nf;System.out.print("Acknowledgmentreceived");
ano=Integer.parseInt(in1.readLine());
System.out.println("for"+ano+"frames");

VAST Dept of Computer Science & Eng. (46)


sws+=nf;
}
else{
System.out.println("Theno.offramesexceedswindowsize");
break;
}
System.out.print("\nDoyouwantstosendsomemoreframes:");
ch=in.readLine();
p.println(ch);
}while(ch.equals("yes"));
s.close();
}
}

RECEIVERPROGRAM:

importjava.net.*;
importjava.io.*;
classslidreceiver
{
publicstaticvoidmain(Stringa[])throwsException
{
Sockets=newSocket(InetAddress.getLocalHost(),10);
DataInputStreamin=newDataInputStream(s.getInputStream());
PrintStreamp=newPrintStream(s.getOutputStream());
inti=0,rptr=1,nf,rws=8;
Stringrbuf[]=newString[8];
Stringch;System.out.println();
do{nf=Integer.parseInt(in.readLine());
if(nf<=rws1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("ThereceivedFrame"+rptr+"is:"+rbuf[rptr]);
}
rws=nf;System.out.println("\nAcknowledgmentsent\n");
p.println(rptr+1);rws+=nf;
}
else
break;
ch=in.readLine();
}while(ch.equals("yes"));
}
}

Output:

SENDER:

administrator@adminSystemsLab:~$javacslidsender.java

administrator@adminSystemsLab:~$javaslidsender

Entertheno.offrames:4

VAST Dept of Computer Science & Eng. (47)


Enter4Messagestobesend

hi...
Thisisnetworklab
Thisprogramdealswithslidingwindowprotocol
Bye

Acknowledgmentreceivedfor4frames

Doyouwantstosendsomemoreframes:yes

Entertheno.offrames:3

Enter3Messagestobesend

Thisprotocoldealswithbulkofframes
Acknowledgmentissendafterreceivingbulkofframes
thankyou

Acknowledgmentreceivedfor7frames

Doyouwantstosendsomemoreframes:no

RECEIVER:

administrator@adminSystemsLab:~$javacslidreceiver.java

administrator@adminSystemsLab:~$javaslidreceiver

ThereceivedFrame0is:hi...

ThereceivedFrame1is:Thisisnetworklab

ThereceivedFrame2is:Thisprogramdealswithslidingwindowprotocol

ThereceivedFrame3is:bye

Acknowledgmentsent

ThereceivedFrame4is:Thisprotocoldealswithbulkofframes

ThereceivedFrame5is:Acknowledgmentissendafterreceivingbulkofframes

ThereceivedFrame6is:thankyou

Acknowledgmentsent

VAST Dept of Computer Science & Eng. (48)


DESIGNEXPERIMENTS
**********
Exp:14

RMINETWORK
Aim:

WriteaJavaprogramtoimplementationofRemotemethodinvocationnetwork


Algorithm:

Server
Step1:Start
Step2:importpackages
Step3:createfunctionadd()withargumentsa1,a2
Step4:returna1+a2
Step5:createnewobjectofrmiserver()'s
Step6:callmethodNaming.rebind()
Step7:print"Registered"
Step8:Stop

Client
Step1:Start
Step2:importpackages
Step3:AssigninbymethodNaming.lookup()
Step4:c=500.38
Step5:d=30.72;
Step6:Printin.add(c,d)
Step7:Stop

Interface

Step1:Start
Step2:importpackages
Step3:callmethodaddwithtwoargumentsa,b
Step4:Stop

Program:

SERVERPROGRAM:

importjava.rmi.*;
importjava.rmi.server.*;
importjava.io.*;
importjava.lang.*;
publicclassrmiserverextendsUnicastRemoteObjectimplementsrmiinter
{
publicrmiserver()throwsRemoteException
{
}
publicdoubleadd(doublea1,doublea2)throwsRemoteException
{
returna1+a2;
}
publicstaticvoidmain(Stringarg[])throwsException

VAST Dept of Computer Science & Eng. (49)


{
rmiservers=newrmiserver();
Naming.rebind("rmi://localhost:1099/test",s);
System.out.println("Registered");
}
}

CLIENTPROGRAM:

importjava.rmi.*;
publicclassrmiclient
{

publicrmiclient()throwsRemoteException
{
}

publicstaticvoidmain(Stringarg[])throwsException
{
rmiinterin=(rmiinter)Naming.lookup("rmi://localhost:1099/test");
doublec=500.38;
doubled=30.72;
System.out.println("TheSumis:"+in.add(c,d));
}
}

INTERFACEPROGRAM:

importjava.rmi.*;
publicinterfacermiinterextendsRemote
{
doubleadd(doublea,doubleb)throwsRemoteException;
}

Output:

SERVER:

administrator@adminSystemsLab:~$javacrmiserver.java

administrator@adminSystemsLab:~$javacrmiinter.java

administrator@adminSystemsLab:~$rmicrmiserver

administrator@adminSystemsLab:~$startrmiregistry

administrator@adminSystemsLab:~$javarmiserver

Registered

CLIENT

administrator@adminSystemsLab:~$javacrmiclient.java

administrator@adminSystemsLab:~$javarmiclient

TheSumis:531.1

VAST Dept of Computer Science & Eng. (50)


Exp:15
PINGCOMMAND
Aim
To write a program in java to demonstrate the usage of PING command.

Algorithm

Pingserver
Step 1: Start
Step 2: Import java.net and other necessary packages.
Step 3 Initialize the ping server with both sockets as null value.
Step 4: Start the server socket.
Step 5: At the client give the IP address of the server.
Step 6: The client program is then started by starting socket.
Step 7: At the receiver end, the client is pinged.
Step 8: Stop the program.

Pingclient
Step8:Start
Step8:Importjava.netandothernecessarypackages
Step8:Initializethepingclientwithbothsocketsasnullvalue.
Step8:Startthesocket
Step8:GettheIPaddressoftheserver.
Step8:Pingtheserver.
Step8:Atthereceiverend,theserverispinged.
Step8:Stop

Program:

PINGSERVER

importjava.io.*;
importjava.net.*;
publicclasspingserver
{
publicstaticvoidmain(Stringa[])
{Stringline1,line2;inti;
ServerSocketes;
DataInputStreamdi;
PrintStreamps;
Socketcsoc;
es=null;
csoc=null;
tr { es=newServerSocket(9999); }
catch(Exceptione)
{ System.out.println(e); }
System.out.println("pingserver");
try { csoc=es.accept();

VAST Dept of Computer Science & Eng. (51)


di=newDataInputStream(csoc.getInputStream());
s=newPrintStream(csoc.getOutputStream());
for(i=0;i<4;i++)
{ line1=di.readLine();
System.out.println("pingedbyclient");
ps.println(line1+"replyfromhost:bytes=3<time<1msTT<=128");
}
di.close();ps.close();
}
catch(Exceptione)
{ System.out.println(e); }
}
}

PINGCLIENT

importjava.io.*;
importjava.net.*;
publicclasspingclient
{
publicstaticvoidmain(Stringargs[])
{ PrintWriterout=null;
inti,j,k;
ufferedReadernetworkIn=null;
try {
System.out.println("entertheIPaddress:");
DataInputStreamin=newDataInputStream(System.in);
Stringip=in.readLine();
Socketthesocket=newSocket(ip,9999);
networkIn=newBufferedReader(newInputStreamReader(System.in));
out=newPrintWriter(thesocket.getOutputStream());
System.out.println("\npinging"+ip+"with32bytesofdata\n");
for(i=0;i<4;i++)
{ out.println(ip);
out.flush();
Stringinp=networkIn.readLine();
if(inp!=null)
{ for(j=0;j<10000;j++)
{ for(k=0;k<50000;k++)
{}
}
System.out.println("replyfrom"+inp);
}
else { for(i=0;i<4;i++)
{ for(j=0;j<10000;j++)
{ for(k=0;k<50000;k++)
{ }
System.out.println("\nrequesttimeout");
}
}
}

}
}
catch(IOExceptione)
{ for(i=0;i<4;i++)
{ for(j=0;j<1000;j++)
{ for(k=0;k<5000;k++)
{ }

VAST Dept of Computer Science & Eng. (52)


}
System.out.println("\nrequesttimedout");
}
}
try {
if(networkIn!=null)
networkIn.close();
if(out!=null)
out.close();
}
catch(Exceptione)
{
System.out.println("\nrequestedtimeout");
}
}
}

Output

PINGCLIENT
administrator@adminSystemsLab:~$javacpingclient.java
administrator@adminSystemsLab:~$javapingclient

entertheIPaddress:
192.168.1.10
pinging192.168.1.10with32bytesofdata
5
replyfrom5
8
replyfrom8
9
replyfrom9
4
replyfrom4
D:\Chitra\Java>

PINGSERVER

administrator@adminSystemsLab:~$javacpingserver.java
administrator@adminSystemsLab:~$javapingserver

pingserver
pingedbyclient
pingedbyclient
pingedbyclient
pingedbyclient

VAST Dept of Computer Science & Eng. (53)


OPENENDEDEXPERIENTS
**********

1.Tosendandreceivemessagefromclientandserverusingconnectionorientedservice.(TalkCommand)
2.Writeaprogramtoimplementafileserverwithsupportforuserauthentication.
3.Writeaprogramtodesignandimplementawebservertoretrieveinformationidentifiedbythe
requestedURL.
4.Towriteajavaprogramtoimplementcyclicredundancycheck.
5.Toperformremotecommandexecution(ie)commandenteredbytheuserattheclientshouldbeexecutedby
theserver.

VAST Dept of Computer Science & Eng. (54)


Lab-In-Charge Head Of Department

You might also like