EXPERIMENT 1
Write an cho program with client and iterative server using TCP.
Solution:-
Iterative Server = An iterative server handles both the comection request and the transaction
involved in the call self) Iterative servers are fairly simple and are suitable for transactions
that donot last kong.
TcPnP
CLIENT SIDE CODING
import java.net
import java.io.*;
public class TepEchoClient
t
Private sialic Socket socket;
able
{
Ss
static void main(String a
in port = 25002;
/*Deteminesyige PPealiess ofa host, given the host's name-*/
InetAddi ress = InctAddress. get ByNa me (host);
gen et address)
oi Socket(address, port);
sd the message to the Server */
OF Stream. os = socket.getOulputStream();
/*Create outputstream writer"!
uiStreamWriter osw = new OutputStreamWritenos);
("Create buffered writer*/
Buffered Writer bw = new BufleredWriter(osw),
/Suring tobe passed*/
String Name = "Akshay";
String serdMessage = Name + "ns
7 writing string to waitee*/
bw. write(sendMessage);
("forces out the characters to string writer*/
bw.flush
‘System outprintIn("Message sent to the server : "+ sendMessage);
/*Open inputstteam for teading purpose*/
InputStream is = socket, getInputStream(;"Create new input stream weader*/
InputStreamReader isr = new InputStreamReader(is);
‘Create new BufleredReader*/
Buflered Reader br = new BufcredReader(isr);
‘Reading fom the sooket*/
String message = br.readl.ino();
System out printin(’ Message received ffom the servei
ccatch (Exception exception)
cexceptionpriniS tack Trace);
finally
{
/*€tosing the socket*/
ty
t
socket.close();
}
catch (Exception e}
t
e.printStack Trace(); ws
} Ss
SERVER SIDE CODING «ON
import java.net; iw)
import java.io.
public class TepEchoS
private & socket;
public si in(Stringl] args)
{
int port = 25002;
S /*Creating ServerSocket*/
WS ServerSocket serverSocket = new ServerSocket(port):
Systemon In("Server Started and listening to the port 25000"),
/* Accepting connestions from Chients*/
socket = serverSocketaccepi();
InputStream is = socket.getInputStream();
InputStreamReader ist = new InputStreamReader(is);
BufferedReader br =new Buflered Reader(isr);
String name = br.readL ine();
Systemout.printIn("Message received fiom cent is "+ name};
/* Manipulating the String*/
String retumMessage = "Hello "+ “Akshay” +" !!\n";
OutputStream os = socket.getOuputStreami),Snapshot of an echo program with client an
new OutputStreamWritertos);
redWriter_ bw = new BufliredWriter(osw);
)
bw.write(returnMes:
Systemout.println("
bw. thish();
sent to the client is " + returnM
catch (Exception ¢)
eprinStackTrace();
finally
; { ) cd
| SS
ie server using TCP.EXPERIMENT- 2
Write an echo program with client and concurrent server using TCP
Solution:-
CLIENT SIDE PROGRAM :-
public cliss MyClient | {
public static void min(Stringf] args) {
try
Scanner s1=new Scanner( System
String mag=new Siring():
Socket s=new Socketi"localhost",6666 );
DataOuipuiSiream dout=new DataOutputStream(s.getOr
dof
msg-sl.nextLine();
out write TFs);
dout.flush();
J while (msgequals("bye")));
Lelose):
seboset xO
}cateh(Exception e){Systemoutprintin()
}
} x
SERVER SIDE ma
import java.net. ey
import java.io.*;
import j
public a |
publi main(String ans{D{
erSocket serversock=new ServerSocket(6666);
»while(truc) {
Socket socket=serversock.accepi();
MyChss obj-new MyClass(sacket
obj.siart();
}
Jeatch(OException ©)f}
1
|
ckss MyClass extends Thread
Socket socket;public MyClass(Socket s){socket = s;}
public vox! run(){
ty
DatalnpuiStream dis-new DatalnputStream( socket. get nputS ream);
String sir;
dof
str=(Stringkis.read UTF ();
System.outprintin("message = "*str):
eateh{IOException e){}
Snapshotof an echo program with client and ene TCP.
«&&Experiment - 03
Write an echo program with client and concurrent server using UDP.
Solution:-
CLIENT SIDE PROGRAM
/* wdpclicnt */
import java.utilSeanner;
import java.io";
import java.net.*;
public class Client {
public static vokd main (String{] args) throws [OException
Scanner se=new Scanner (Systemin);
int port =|
InetAddress host = InctAddress.getByName_("
DatagramSocket socket = new DatagramSoc
socketseiSoTimeout (5000);
‘/DatagramPacket(bytel], int, InctAdd
DatagramPacket_ packet = new “AS SW byte[256], 1, host, port);
byte[] outBufler = se.nextLi ave ,
packetsetData (out
packetsetLength (outBullgr.tengih);
sacket.send (packet);
socket receive (pacl
sacket.close ey
ee
Na Poca »
r of
import\java.io.";
import java.net.*;
public css Server {
public static final int DEFAULT_PORT = 13;
public static void main (String(} args) throws IOException {
DatagramSocket socket = new DatagramSocket
(DEFAULT PORT );mPacket packet = new Da
while (true) {
socket.receive (packet);
Systemout.printin
(Received fiom:
byte[] outBufler = new java.util Date (.toSti
Packet (new byte[1}, 1):
packet. getPort Q)
tBytes();
packet.setData (outBufter);
packetsetLength (outBuffer.length);
socket.send (packet);
Snapshotof an an echo program with client and co
UDP,EXPERIMENT - 04
Write a client and server program for chatting
Solution:-
CLIENT SIDE PROGRAM:
/* chat chem */
import java.io.*;
import java.net Socket;
import java.net SocketException;
import java.net. UnknownHostE xception;
public chiss ChatSocketC bent {
private Socket socket = null
private InputStream inStream
Private OutpuStream outStream = null
public void createSocket(}t
nyt
‘outStream = socket. getOuy
createReadThread(); Ty
createWriteThread();
Jcatch (UnknownHostExcepijbit u)
{
wy
} catch (I
wee Os
iteRead Thread()
readThread = new Thread()
public void run()
t
while (socket.isConnected())
t
ty t
byte[] readBufler = new byte[200];
int num = inStream read(readBufler);
if (rum > 0) {
byte[] arrayBytes = new bytefimur);Systemarmaycopy(read Buffer, 0, arrayBytes, 0, num);
String reevedMessage = new String(arrayBytes, "UTF=8");
Systemout.printin("Server :" + reevedMessage);
ae
Jeatch (SocketException se)
1
Systemexit(0};
}
catch (IOException )
iprintStack Trace();
}
)
h
readThread.setPriority( Thread. MAX_PRIORITY );
read Thread. start();
}
public void createWriteThread () {
‘Thread writeThread = new Thread(){
public void run(){
whik (socket.isConnected()) |
yt
Buffered Reader inputReader Rtas
InputStreamReader(System.in));
skep(100);
String typedMessage # jer.readLine();
if (typedMessage 1 && typedMessage.lengtht) > 0)|
synehronil y
‘outS treat. writer y fled Message. getB ytes("UTF-8"));
‘skeep(100)
1
QD
QS M
stack Trace();
itch{ Interrupted Exception ic}{
WS ie.prinStackTraceQ);
1
}
}
i
write Thread setPriority( Thread. MAX_PRIORITY);
‘write Thread start();
}
public static void main(String{] args)throws Exception {
ChatSocketClnt myChuClient =new ChatSocketClent();
myChatClient.createSocket();SERVER SIDE PROGRAM:=
import java.io";
import java.net ServerSocket;
impont java.net Socket;
import java.net SocketException;
public kiss ChatSocketServer |
private ServerSocket severSocket = null;
private Socket socket = null
private InputStream inStream =
Private OutputStream, outStream
public ChatSocketServer()
}
public void createSocket()f
ty f
‘ServerSocket serverSocket = new Sees
while (irae)
socket = serverSacketaccept();
inStream = socket,getInputStream(); RAN
outStream = socket.getOuputStreamgy,
Systemout.printin("Connected"), mex
createReadThread(); iN
create Write Thread();
) an
}eatch (IOException io){
io printS tack Trace(); S
' GS
}
public void ereateRe; Ot
Thread rea Thread(){
public vol
whil Connected )){
] readBufler = new byte[200);
SS num = inStream read(readButfer);
WS if (rum > 0) |
byte[] armayBytes = new byte[mum];
Systemamayeopy(read Buller, 0, arrayBytes, 0, num);
String reevedMessage = new String(arrayBytes, "UTF-8");
nt" +reevedMessage);
iSystemarraycopy();
} catch (SacketException so){
Systemexi(0);| catch (OException ){
ipriniStack Trace():
}
}
}
ig
readThread.setPriority(Thread. MAX_PRIORITY);
read Thread, start();
1
Public void createWriteThnead () |
‘Thread writeThread = new Thread) {
public void run() |
while (socket.sConnected()) {
try
BufferedReader inputReader = new BufleredReader(new
InputStreamReader(System.in));
sleep(100);
String typedMessage = inputReader.readL ine(
if (typedMessage '= mil && typedMessay
synchronized (socket)
coutStrcam write( typedMessage. PB):
skep(100); x
}cateh( Interrupted Except aN
conn
S MAX_PRIORITY):
‘tring{] args){
chatServer = new ChatSocketServert);
leSocket();Snapshot of a client and server program for chattingEXPERIMENT :-05
Write a program to retrieve date and time using TCP.
Solution:-
CLIENT SIDE PROGRAM:
/** Top day client **/
public class Tepdayclient
public static void main(String arg{)throws IOException{
uyt
Socket s=new Socket("hocalhost".6432);
DatalnpurStream ds=new DatalnpaStreams,getnp
String msg:
meg= dis readUTFO;
Systemout.printin(msg);
dis.close():
s.chose();
Jeatch(Exception ¢)
{Systemout. print ln{c);}
'
SERVER SIDE ae
("day server
publ e lterServer _{
public static void main(String{] args) {
ryt
ServerSacket ss-new ServerSockei(6432);
Socket smssaaccepl();
Date dt new java.util Date(;
DataOutputSteam dout-new DataQutputStream(s.getOutputStream()h,
String str;
str=dLtoString();
doutwriteLTF(ste);ss.close();
catch(Exception ¢)
(Systemout.printIn(e};}
Snapshotof a program to retrieve date and time using TCP. NS
aEXPERIMENT- 06
Write a program to retrieve date and time using UDP.
Solution:-
CLIENT SIDE PROGRAM:-
udp day cent */
import java.io.*;
import java.net;
public chiss DaytimeChient_{
public static void main (String{] args) throws IOException {
if ((args.kength != 1))
throw new HlegalArgumentException
("Syntax: DaytimeClient host");
int port = 13;
InetAddress host = InctAddress,getByName (“locglh
DatagramSocket socket = new DatagramSocke
socketsetSoTimeout (5000),
WDatagramPacker(bytef], int, InetAdal
DatagramPacket_ packet = new Datagramhgeket (mew byte[256], 1, host, port);
socket.send (packet);
packet.setLength (packet getDa
socketreceive (packet);
socketcbse ();
byte{] data = rig
int length = packet.
Systemout.printin (1 (data)y;
1
}
public chiss DaytimeServer {
public static final int DEFAULT PORT = 13:
public static void main (Strine[] args) throws IOException {
DatagramSocket socket = new DatagramSocket (DEFAULT_PORT );
DatagramPacket packet = new DatagramPacket (new byte[1], 1);
while (true) |
socket.receive (packet);
Systemoutprintin("Received + packet.getAddress ()
byte] outBuller = new javatil Date (toString 0g
cketgetPart ()
Bytes();
packet.setData (outBufler);
packet.setLength (outBufler.lengih);
socket.send (packet);
pshot of a program to retrieve date and time "EXPERIMENT 7
Write a client and server routines showing Blocking 1/0.
Server Proram.
package crunchify.com.tuorials;
import java.io. OException,
import java.net InetSocketAddress;
import java.nio. ByteBufler;
import java.nio.channels.Se ketionKey;
import java.nio, channels, Selector;
import java.nio.channels,ServerSocketChannek,
import java.nio.channels.SocketChanne|;
import java.util erator,
import java.util Set;
pe
* @author Crunchify.com
*
public ckss CrunchifyNIOServer { J
‘@SuppressWamings(""unused
public statie void main(S any) throws IOException {
#/ Selector: e f SelectableChannel objects
Sekctor seleciOn= S@ecior.opert); // selector i open here
Ww hanne!: selectable channel for stream-oriented listening
sockets
Se cetChanne! crunchifySocket = ServerSocketChanneLopen();
{iggetktA dress erusifyAdr ~ now netSocke dre "ocaos
Hy SS
// Binds the channets socket to a local address and configures the socket to
lst mections
erunchifySocket bind(crunchifyAddrp;,
4 Adjusts this channe?s blocking mode.
crunchifySocket. configure Block ing{ fa ke);
int ops = crunchifySocket.alidOps();
SeketionKey selectKy = crunchifySocket register(selector, ops, mull;
(Infinite loop...
(Keep server runningwhile (true) {
log("?m aserver and im waiting for new connection and buffer
1/ Selects a set of keys whose corresponding channels are ready for VO
sekector.select();
W/token representing the registration ofa SelectableChannel with a
whike (crunchifylterator.hasNext() {
SelectionKey myKey = crunchifylterators
J Tests whether this key's channel gre:
socket connection
if (mpKey.isAcceplable()) §
SocketChannel ci =
crunchifySocketaccept();
1 Adi 5 blocking mode to false
crunchif igureBlock ing false);
y set bit for read operations
lient. register(selector,
SekectionKey.OP_READ),
Connection Accepted: * +
cerunchifyC lient. getLocalAddfesst I":
1) Tests whether this key's channe! is ready for reading
y cee if (myKey.isReadable()) |
QS SocketChannel crunchifyClient = (SocketChanne
myKey.chanpel()
ByteBulfer ctunchifyBulfer = ByteBufferalincate(256);
crunchifyC lient. read{crunchifyBufter);
String resul
st hifyBuffercarray()). trim);
Jog("Message received: * + result);
if (resultequals(*Crunchity")) {
cerunehifyC tient.close();
log("inl’s. time to close connection as we got
last company name 'Crunchify’
log\nServer will keep runing. Try running
cent again to establish new connection");
}‘crunchifylterator. remo ve();
}
private static void logiString str) {
System out printIn(str);
1
}
Client Program,
package crnchify.com tuorials;
import java.io IOException;
import java.nct.InetSocketAddress;
import java.nio. ByteBuller;
import java.nio.channe ls. SocketChanne |;
import java.util ArrayList;
pe
* @author Crunchify.com
i S
public class CrunchifyNIOClient
public static void ma ) throws IOException, InterruptedException {
InetSocketAddress cruncht new InetSocketAddress("loea hast", 111
SovketChannel_ crunchif¥G ight. = SocketChanneLopen(crunchify Addr);
ig 10 Server on port 1111..."
AmrayList
();
NOR. a AnayList with companyName fist
companyDelails.add(""Facebook");
companyDeiails.add("Twitter");
companyDetails.add("IBM":
companyDeiails.add("Goo ke");
companyDetnils.add("Crunchi fy");
for (String companyName ; companyDetails) §
byte[] message = new’ String{companyName), gctB ytes();
ByteBufer buffer = ByteBuffer.wrap(message);
‘erunchifyC lient. (bufer);
log("sending: " + companyName);butlér.clear();
wait for 2 seconds before sending next messa
Thread skeep(2000),
chunchif\C lient.clase();
private static void logiString str) {
System out.printin(str);EXPERIMENT 8
Write a client and server routines showing /O multiplexing.
Solution
SERVER SIDE CODING
finchde
‘inelude
#include
#incude
#inelnde
iinclude
iinclude
#incude
fidefine MAXLINE 20
define SERV_PORT 7134 ne
main(int arge,char **argy) S
t
int ij,maximaxfa, listenfd,connf,sock fds
int nread,client{D_SETSIZE];
ssize_t ny S
fa_set rset.allset; SN
‘char line{MAXLIN E};
socklen_t elilem
_STREAM.0):
inca! idr)}; servaddr.sin_fimily=AF_INET;
senvaddrsin_porigfidys(SERV_PORT);
bind(listenfd addr *)&eservaddr,sizeoflservaddr));
listens
cl
fort; 3)
|
rset=alket;
nread=select(max il+1,derse, NULL,NULL,NULL);
iF D_ISSET(listentl &erset))
{
clilen=sizco Relinddr);
conniil=accepi(listenfil(struct. sockaddr* eliaddr,&ec lien
for(i-0simaxf). maxfd=eonn fal;
i> maxi)
maxi,
il=nread<=0)
ccontione;
\
for(i=0;ic=maxisit+)
{
if(sockt=client{il)<0)
continue;
iFD_ISSET (sock fl dersct))
t
if{(n=read( sock a, line,M.
close(sockfi);
eee
celient{ i}=- 1; WS
CLIENT SIDE CODING
‘#includecnetine vin. >
#include
finclude
finchude=stdlib. h>
iinclude
#inchude=sys/sock et. he>
#include#inchude=unistd.h>
efine MAXLINE
SERV_PORT
main(int arge,char **argy)
0
int maxflpl;
fa_set rset
‘char sendline[MAXLINE],reevline[MAXLINE|
"usage tepeli
include
ffinelude
‘include
#incude
#inelude
‘inelude
include
include
unis. tcp server
int main()
{int sock, connected, bytes_reciewed , true = I;
char send_data [1024]=f"Hello User!!") , recy_data{ (02,
stuet sockaddr_in server_addr,client_addr;
imt sin si
if ((sock = socke(AF_INET, SOCK_STREAM, 0)—= -1) |
perror("Socket”);
exit(); SN
wy
if (setsockoptt{sock,SOL_SO} my FUSEADDR,dtruesizeaftint)) =
perror("Setsockopt");
vexit( 1); OS
i
server_addr.sin_famlps= XP? INET;
i
‘in_zero),8);
t sockaddr *)&server_addr, sizeof{struct: sackaddr)) == -1) {
printf("\nTCPServer Waiting for efent on port 5000");
fflush(stdout);
sin_size = sizwoflstruct sockaddr_in);
connected = accepi(sock, (struct sockaddr *)éeclient_addr,dtsin_s
printi"\n I got a connection fiom (%s , %d)\n",
inet_ntoa(lient_addr.sin_addr), ntohs{c lient_addr.sin_port));
send(connected, send_data,strlen(send_data), 0);close( connected);
close(sock);
retum 0;
}
Hiunis tep client
iinelude
ivinelude
‘finelude
‘include
include
‘include
include
iéinelude
iinelude
‘int main()
t
int sock, bytes_recieved;
char send_dataj 1024],recv_data[ 1024];
struct hostent *host;
stnict sockaddr in server_addr,
host = gethostbyname("127.0,
if ((sock = socke(AF_INET,
perror("Socket");
exit( 1);
i
server_addr-sin_addr
baero(@elserver_addr si
if (conneci(sock, (ayufebgockaddr *eserver_addr,
sizeo oS i) = -1)
{
CONT:
xo
+ Teev_data);
wsend(sock,send_datastrlen(send data), 0);
close(sock);
return 0;Snapshotof an echo client and server program using Unix domain Stream
socket.EXPERIMENT- 10
Write an echo client and server program using Unix domain Datagram socket.
include
include
include
include
include
include
include
include
‘include
int main()
t
imt sock;
im addr_len, bytes_read;
char reev_data{ 1024);
struct sockaddr_in server_addr , client_addr;
if (sock = socke(AF_INET, SOCK_DGRAM, 0)) —@ -
perror("Socket");
cexi( 1),
i
server_addr.sin_family = AF_INET,
server_addrsin_port = htons(S000).
server_addr.sin_addr.s_addr
bacro(ae(server_addr.sin_zera8):
if (bind(sock,(stenet socks
‘siecof{struct a
t
perron("Bind");
exit); &
y
addr_en QS 1 sockaddr);
PServer Waiting for client on port 5000");
= reevifom{sock,reev_data,1024,0,
(struct sockaddr *)&chent_addr, &addr_len);
recv_datafbytes_read] ="O';
prin("\n(%s . Yad) said : "net_ntoa(elient_addr.sin_addr),
nlohs(client_addr.sin_port));
print "s\n", recy_data);
fMhush(stdour);
retum 0;
}
J/ unix, udp clientifinelude
include
‘include
ffinclude
finelude
‘finelude
‘finelude
finelude
‘include
\
imt sock; XS
struct sockaddr in server_adde;
siruct hostent *host S
char send_data[ 102 G
host= (struct hastent *) gcthostbyname( (char *)°127.0.0.1%
if ((sock = socketAF_INET, SOCK_DGRAM, 0))
server_addr.sin_family = AF_INI AN
server_addr.sin_port = Itons(S000); XO
a *((struet_ addr *Ypost->h_addley,
baero(&e(server_addr.sin_zet0),
print” Type Something iw
gets(send_data);
sendto(sock, Tsend_data), 0,
(struct sockaddr we ddr, sizeostruct. sockaddr)),
a
wD echo client and server program using Unix domain
Da eket.EXPERIMENT 11
Write a client and server program to implement file transfer.
Solution
SERVER SIDE CODING
import java.io.BufféredinputStream;
import java.io.File;
import java.io.Filel nputS team;
import java.io.1OException;
import java.io, OutputStream;
import java.net ServerSocket;
import java.net Socket,
public class TCPFikeTransferServer {
public static void main(S
ServerSocket servsoe
File myFile = new File("C2/Users/sweeto
while (true)
‘Systemout.printn( "Waiting. fir eB
‘Socket sock = servsock.accept SS
‘byte[] mybytearray = new ZN ike.engtho)];
BufferedinputStream bis