Professional Documents
Culture Documents
Thalakkottukara
Thrissur, Kerala 680 501
Ph. (91) 04885 287751, 287752
www.vidyaacademy.ac.in
A unit of
Vidya International Charitable Trust
CS09708(P):NETWORKPROGRAMMINGLAB
Teacher'sCopy
SYLLABUS
Objectives
Lab 2,3 : Software Simulation of IEEE 802.3, 802.4 and 802.5 protocols.
1) GoBackN,
3) Sliding Window.
Reference Books
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
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
SocketprogramingwitthTCP/IP
processrunningondifferentmachinesconnwitheachotherbysendingmessageintosockets.Wesaid
thateachprocesssocketisanalogoustoahouseandtheprocess'ssocketisanalogoustoadoorasshownin
fig.2.ThesocketisanalogoustoadoorbetweenapplicationprocessandTCP.Theapplicationdeveloperhascontrol
ofeverythingontheapplicationlayersideofsocket.However,ithaslittlecontrolofthetransportlayerside.
socket Socket
Fig.2ProcessCommunicatingthroughTCPports
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
*********
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:");
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..
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();
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..
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
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)
{
}
}
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){}
}
Output:
Sendmessagetoclient
messagefromclient:hai
messagefromclient:hai
messagefromclient:howareyou?
messagefromclient:Imgood,Whataboutu?
messagefromclient:Imfine,thankyou
messagefromclient:yah!
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");
}}
}
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);
Output:
TwowayCommunication
RecievedText:hai
EnterText:
hello
RecievedText:howru?
EnterText:
Fine..!
RecievedText:
end
EnterText:
end
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"));
}}
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++)
Output:
Connected
Serverstarted
client0:TheWorldatyourfingertips..!!!
Exit
client1:TheWorldatyourfingertips..!!!
Exit
client2:TheWorldatyourfingertips..!!!
Exit
client3:TheWorldatyourfingertips..!!!
Exit
client4:TheWorldatyourfingertips..!!!
Exit
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;
Client:
importjava.io.*;
importjava.net.*;
publicclasspcclientimplementsRunnable
{
}
}
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
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
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
Output:
Serverside:
:getfiley.txt...
:putfilex.txt...
..transfer....x.text..
Clientside:
Enterthecommand:get|file|/put|file|
gety.txt
y.txt
...get..y.txt..
ftpclient
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.
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.
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;
StopwaitServer.java
importjava.io.*;
importjava.net.*;
publicclassStopwaitServer
{
ServerSocketss;
Sockets;
BufferedReaderbr;
PrintWriterpw;
Threadt1,t2;
intcount=0;
StringstrSnd=newString("ACK");
}
publicstaticvoidmain(String[]arg)
{ StopwaitServerserv=newStopwaitServer();
serv.windowProcess();
}
}
Output:
Serverside:
ServerStarted..
Clientconnected
TESTDATA
ReceivedDATA0
AcknowledgedforDATA0sent
TESTDATA
ReceivedDATA1
AcknowledgedforDATA0sent
TESTDATA
TESTDATA
ReceivedDATA3
AcknowledgedforDATA0sent
TESTDATA
ReceivedDATA4
AcknowledgedforDATA0sent
ClientSide:
ClientStarted...
SendingDATA0
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0
SendingDATA1
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0
SendingDATA2
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0
SendingDATA3
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0
SendingDATA4
Senderwaitingforacknowledgement
AcknowledgementreceivedforDATA0
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
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++;
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();
Output:
ServerSide:
Serverstarted...
ClientConnected
DataRecieved0
Acknowledged0
DataRecieved1
Acknowledged1
DataCorrupted2
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);
//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">
<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>
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/>
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;
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.*;
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
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
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");
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
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
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
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
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();
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++)
{ }
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
1.Tosendandreceivemessagefromclientandserverusingconnectionorientedservice.(TalkCommand)
2.Writeaprogramtoimplementafileserverwithsupportforuserauthentication.
3.Writeaprogramtodesignandimplementawebservertoretrieveinformationidentifiedbythe
requestedURL.
4.Towriteajavaprogramtoimplementcyclicredundancycheck.
5.Toperformremotecommandexecution(ie)commandenteredbytheuserattheclientshouldbeexecutedby
theserver.