Académique Documents
Professionnel Documents
Culture Documents
What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is
bound to a specific port number. The server just waits, listening to the socket
for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on
which the server is running and the port number to which the server is
connected. To make a connection request, the client tries to rendezvous with
the server on the server's machine and port.
The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program
and another program on the network. The Socket class sits on top of a
platform-dependent implementation, hiding the details of any particular
system from your Java program. By using the java.net.Socket class instead of
relying on native code, your Java programs can communicate over the
network in a platform-independent fashion.
-1-
Msc I.T Part I Advanced Computer
Networks
Syntax:
To open a socket Socket:
Socket MyClient;
Myclient = new Socket(“Machine name”, PortNumber);
When Implementing server you also need to create a socket object from the
ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null;
try {
serviceSocket = Myservice.accpt();
}
catch(IOException e){ System.out.println(e); }
-2-
Msc I.T Part I Advanced Computer
Networks
UDP UDP
client server
internet Host B
Host A
Because of this, the amount of data that can be sent in a UDP packet is
limited to the amount that can be contained in a single IP packet. Thus, a
UDP packet can contain at most 65507 bytes (this is the 65535-byte IP
packet size minus the minimum IP header of 20 bytes and minus the 8-byte
UDP header). UDP packets can arrive out of order or not at all. No packet has
any knowledge of the preceding or following packet. The recipient does not
acknowledge packets, so the sender does not know that the transmission
was successful. UDP has no provisions for flow control--packets can be
received faster than they can be used.
So why use UDP if it unreliable? Two reasons: speed and overhead. UDP
packets have almost no overhead--you simply send them then forget about
them. And they are fast, since there is no acknowledgement required for
-3-
Msc I.T Part I Advanced Computer
Networks
each packet. Keep in mind the degree of unreliability we are talking about.
For all practical purposes, an Ethernet breaks down if more than about 2
percent of all packets are lost. So, when we say unreliable, the worst-case
loss is very small. UDP is appropriate for the many network services that do
not require guaranteed delivery. An example of this is a network time
service. Consider a time daemon that issues a UDP packet every second so
computers on the LAN can synchronize their clocks. If a packet is lost, it's no
big deal--the next one will be by in another second and will contain all
necessary information to accomplish the task. Another common use of UDP is
in networked, multi-user games, where a player's position is sent
periodically. Again, if one position update is lost, the next one will contain all
the required information. A broad class of applications is built on top of UDP
using streaming protocols.
That would result in a very choppy, bursty playback which most people
find unacceptable, and which would place a heavy demand on the server.
Practical 1
-4-
Msc I.T Part I Advanced Computer
Networks
Aim: Write a client server program that will display the IP address and
the local host address.
Description:
java.net provides addressing-related class InetAddress for IP addressing.
Class InetAddress represents an IP address, which is either a 32- or 128-bit
unsigned number used by IP, the lower-level protocol on which protocols like
TCP and UDP are built.
Server Program:
import java.io.*;
import java.net.*;
public class inetServer
{
public static void main(String a[])
{
System.out.println("Starting Server...WAIT....");
try
{
ServerSocket srv = new ServerSocket(5555);
System.out.println("Server Started : " + srv);
Socket clt = srv.accept();
InetAddress cltAddress = clt.getInetAddress();
System.out.println("Client IP : "+ cltAddress.getHostAddress() +
"\tPort no : "+ clt.getPort());
PrintStream ios = new PrintStream(clt.getOutputStream());
ios.println("Server address is : " + srv);
ios.close();
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}
Client Program:
import java.net.*;
import java.io.*;
public class inetClient
{
public static void main(String ss[])
{
-5-
Msc I.T Part I Advanced Computer
Networks
try
{
InetAddress inetaddr = InetAddress.getLocalHost();
Socket sock =new Socket (inetaddr,5555);
System.out.println("Connection Established to Server");
InputStreamReader input = new InputStreamReader
(sock.getInputStream());
BufferedReader buffreader = new BufferedReader(input);
System.out.println(buffreader.readLine());
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}
-6-
Msc I.T Part I Advanced Computer
Networks
Practical 2
-7-
Msc I.T Part I Advanced Computer
Networks
Description:
On the client side:
Numbers is accepted from the user through “InputStreamReader(System.in)”
which allows to read line of text and sent to server by opening socket client
side and send the numbers to the server through “PrintWriter” and
“OutputStreamWriter”. Output is sent from server and received by client
using “PrintWriter”
On the server side:
First ServerSocket is created and waits client to open the socket that is
“ss.accept()”. The result is sent from client and calculation is done by server.
The output is sent to client side using “pw.println(Number " +n + " is greater
than " +m);”
Server Program:
import java.io.*;
import java.net.*;
class TCPServerGreater
{
public static void main(String arg[])
{
Socket s;
int port=9999,n,m;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for client");
s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(s.getOutputStream())) ;
String str1=br.readLine();
String str2=br.readLine();
n=Integer.parseInt(str1);
m=Integer.parseInt(str2);
System.out.println("First Number recieve from client: " + n);
System.out.println("Second Number receive from client: " + m);
if (n > m)
pw.println("Number " +n + " is greater than " +m);
else
pw.println("Number " +m + " is greater than " +n);
pw.flush();
pw.close(); br.close();
s.close(); ss.close();
}
-8-
Msc I.T Part I Advanced Computer
Networks
catch(Exception e) { }
}
}
Client Program:
import java.io.*;
import java.net.*;
class TCPClientGreater
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
System.out.print("Enter the First Number: ");
String str1=br.readLine();
System.out.print("Enter the Second Number: ");
String str2=br.readLine();
pw.println(str1);
pw.println(str2);
pw.flush();
msg=br1.readLine();
System.out.println("Answer from server : ");
System.out.println(msg);
}
catch(Exception e) { }
}
}
Output of Server Program:
-9-
Msc I.T Part I Advanced Computer
Networks
Practical 3
- 10 -
Msc I.T Part I Advanced Computer
Networks
Description:
On the client side:
A number is accepted from the user through ‘InputStreamReader(System.in)’
which allows to read line of text and sent to server using ‘ DatagramPacket
outDgp = new DatagramPacket
(numbers.getBytes(),numbers.length(),host,port)’ and ‘client.send(outDgp)’.
Output is sent from server and received by client using ‘ DatagramPacket
inDgp =new DatagramPacket (buffer,buffer.length)’ and
‘client.receive(inDgp)’
On the server side:
A number is sent from client and calculation is done by server. The output is
sent to client side using ‘DatagramPacket outDgp=new DatagramPacket
(rsp.getBytes() ,rsp.length() ,senderAddress ,senderPort)’ and
‘ss.send(outDgp)’
Server Program:
import java.io.*;
import java.net.*;
public class UDPServerFactorial
{
public static void main(String args[])
{
int port =7896;
try
{
DatagramSocket ss=new DatagramSocket(port);
byte[] buffer =new byte[256];
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
String req,rsp;
System.out.println("Waiting for client");
ss.receive(inDgp);
InetAddress senderAddress =inDgp.getAddress();
int senderPort =inDgp.getPort();
req=new String(inDgp.getData(),0,inDgp.getLength());
int fact=1;
int num=Integer.parseInt(req);
System.out.println("Number receive from client: "+num);
for(int i=2;i<=num;i++)
fact=fact*i;
rsp="Factorial of the number is "+ fact;
DatagramPacket outDgp=new
DatagramPacket(rsp.getBytes(),rsp.length(),senderAddress,senderP
ort);
ss.send(outDgp);
ss.close();
}
- 11 -
Msc I.T Part I Advanced Computer
Networks
Client Program:
import java.io.*;
import java.net.*;
public class UDPClientFactorial
{
public static void main(String args[])
{
InetAddress host;
int port=7896;
try
{
host = InetAddress.getLocalHost();
DatagramSocket client=new DatagramSocket();
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a Number : ");
String Numbers=br.readLine();
DatagramPacket outDgp =new DatagramPacket
(Numbers.getBytes() ,Numbers.length(),host,port);
client.send(outDgp);
byte buffer[]=new byte[256];
DatagramPacket inDgp =new
DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new
String(inDgp.getData(),0,inDgp.getLength());
System.out.println("Answer from server:");
System.out.println(rsp);
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//End of main
}
Output of Server Program:
- 12 -
Msc I.T Part I Advanced Computer
Networks
Practical 4
- 13 -
Msc I.T Part I Advanced Computer
Networks
Description:
Basics in this program:
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.
Server Program:
import java.io.*;
import java.net.*;
class TCPServerEcho
{
public static void main(String arg[])
{
Socket s;
int port=9999,count=0;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Echo Server Started... \n Waiting for Client");
s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader
(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter
(s.getOutputStream())) ;
while(true)
{
String str=br.readLine();
if (str.equals("bye")) System.out.println("Client
Terminated");
System.out.println("Message from the Client: "+str);
pw.println(str.toUpperCase());
pw.flush();
}
pw.close();
br.close();
s.close();
ss.close();
}
catch(Exception e) { }
}
}
Client Program:
import java.io.*;
import java.net.*;
class TCPClientEcho
- 14 -
Msc I.T Part I Advanced Computer
Networks
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
while(true)
{
System.out.print("Message: ");
String str=br.readLine();
pw.println(str);
pw.flush();
if(str.equals("bye")) System.exit(0);
msg=br1.readLine();
System.out.println("Echo: " + msg);
}
br1.close();
pw.close();
osw.close();
s.close();
ss.close();
}
catch(Exception e) { }
}
}
- 15 -
Msc I.T Part I Advanced Computer
Networks
Practical 5
- 16 -
Msc I.T Part I Advanced Computer
Networks
Server Program:
import java.io.*;
import java.net.*;
public class UDPServerEcho
{
public static void main(String args[])
{
int port =7896;
try
{
DatagramSocket ss=new DatagramSocket(port);
byte[] buffer =new byte[256];
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
String req,rsp;
System.out.println("Waiting for client");
while(true)
{
ss.receive(inDgp);
InetAddress senderAddress =inDgp.getAddress();
int senderPort =inDgp.getPort();
req=new String(inDgp.getData(),0,inDgp.getLength());
if(req.equals("bye"))
System.out.println("Client Terminated");
ss.close();System.exit(0);
System.out.println("Message from Client: " + req);
rsp=req.toUpperCase();
DatagramPacket outDgp=new DatagramPacket (rsp.getBytes()
,rsp.length(), senderAddress ,senderPort);
ss.send(outDgp);
}
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}
Client Program:
import java.io.*;
import java.net.*;
- 17 -
Msc I.T Part I Advanced Computer
Networks
try
{
host = InetAddress.getLocalHost();
DatagramSocket client=new DatagramSocket();
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
System.out.print("Message: ");
String str1=br.readLine();
DatagramPacket outDgp =new DatagramPacket
(str1.getBytes(), str1.length(), host,port);
client.send(outDgp);
if(str1.equals("bye"))
System.out.println("Client Terminated"); break;
byte buffer[]=new byte[256];
DatagramPacket inDgp =new
DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new String(inDgp.getData(),0,inDgp.getLength());
System.out.println("Echo: " + rsp);
}
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//End of main
}
- 18 -
Msc I.T Part I Advanced Computer
Networks
Practical 6
Aim: Create an iterative connection-oriented server.
- 19 -
Msc I.T Part I Advanced Computer
Networks
Server Program:
import java.io.*;
import java.net.*;
class TCPServerFactorial
{
public static void main(String arg[])
{
Socket s;
int id;
int port=9999,count=0;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for client");
s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter
(s.getOutputStream())) ;
while(true)
{
String str=br.readLine();
if (str.equals("bye"))
System.out.println("Client Terminated");
int n=Integer.parseInt(str);
int i,f=1;
System.out.println("Number receive from client: " + n);
for(i = 2; i <= n; i++)
f = f * i;
pw.println("Factorial is : "+f);
pw.flush();
}
}
catch(Exception e) { }
}
}
Client Program:
import java.io.*;
import java.net.*;
class TCPClientFactorial
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
- 20 -
Msc I.T Part I Advanced Computer
Networks
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
while(true)
{
System.out.print("Enter a Number (bye to EXIT): ");
String str=br.readLine();
pw.println(str);
pw.flush();
if(str.equals("bye"))
System.exit(0);
msg=br1.readLine();
System.out.println("Answer from server : ");
System.out.println(msg);
}
br1.close();
pw.close();
osw.close();
s.close();
ss.close();
}
catch (Exception e) { }
}
}
- 21 -
Msc I.T Part I Advanced Computer
Networks
Practical 7
Server Program:
import java.io.*;
import java.net.*;
import java.lang.*;
public class UDPServerPalindrome
{
public static void main(String args[])
{
int port =7896;
try
{
- 22 -
Msc I.T Part I Advanced Computer
Networks
Client Program:
import java.io.*;
import java.net.*;
- 23 -
Msc I.T Part I Advanced Computer
Networks
- 24 -
Msc I.T Part I Advanced Computer
Networks
Practical 8
Server Program:
import java.io.*;
import java.net.*;
- 25 -
Msc I.T Part I Advanced Computer
Networks
- 26 -
Msc I.T Part I Advanced Computer
Networks
for( ; ;)
{
Socket clt = srv.accept();
StringThread st = new StringThread(clt);
st.start();
}
}
}
Client Program:
import java.io.*;
import java.net.*;
- 27 -
Msc I.T Part I Advanced Computer
Networks
{
System.out.println("Error"+ e.toString());
}
}
}
- 28 -
Msc I.T Part I Advanced Computer
Networks
Practical 9
Server Program:
import java.io.*;
import java.net.*;
import java.util.*;
- 29 -
Msc I.T Part I Advanced Computer
Networks
Client Program:
import java.io.*;
import java.net.*;
class UDPPalindromeClient
{
public static void main(String args[])throws Exception
{
DatagramSocket server=new DatagramSocket();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress add=InetAddress.getLocalHost();
byte send_buff[]=new byte[1024];
byte rec_buff[]=new byte[1024];
- 30 -
Msc I.T Part I Advanced Computer
Networks
DatagramPacket rec_dp=new
DatagramPacket(rec_buff,rec_buff.length);
server.receive(rec_dp);
String result=new String(rec_dp.getData());
result=result.trim();
System.out.println("\n"+result+"\n");
if (s.equals("X") || s.equals("x") )
{
br.close();
server.close();
System.exit(0);
}
}
}
}
- 31 -
Msc I.T Part I Advanced Computer
Networks
- 32 -
Msc I.T Part I Advanced Computer
Networks
Practical 10
Description:
Server Program:
import java.io.*;
import java.net.*;
class TCPFileServer implements Runnable
{
public static void main(String args[])throws Exception
{
TCPFileServer fserver=new TCPFileServer();
Thread t=new Thread(fserver);
t.start();
}
public void run()
{
InputStream is=null;
OutputStream os=null;
BufferedReader in_net=null, file_read=null;
PrintWriter pw=null;
ServerSocket server=null;
Socket client=null;
try
{
System.out.println("Server Started\n");
server=new ServerSocket(30033);
client=server.accept();
System.out.println("Client Connected\n");
is=client.getInputStream();
os=client.getOutputStream();
in_net=new BufferedReader(new
InputStreamReader(client.getInputStream()));
pw=new PrintWriter(os);
String s,file_name;
file_name=in_net.readLine();
file_name=file_name.trim();
File f=new File(file_name);
if (f.exists())
{
file_read=new BufferedReader(new FileReader(f));
while ((s=file_read.readLine()) != null)
{
- 33 -
Msc I.T Part I Advanced Computer
Networks
pw.println(s);
pw.flush();
}
file_read.close();
}
System.out.println("File Flushed");
in_net.close();
client.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client Program:
import java.io.*;
import java.net.*;
import java.lang.*;
- 34 -
Msc I.T Part I Advanced Computer
Networks
String new_filename;
System.out.print("\nEnter New File Name: - ");
new_filename=ins.readLine();
new_filename=new_filename.trim();
String new_file=new_filename+file_ext;
String userinput;
File f=new File(new_file);
FileWriter sp=new FileWriter(f);
while((userinput = d.readLine())!=null)
{
System.out.println(userinput);
sp.write(userinput);
sp.flush();
Thread.sleep(1000);
}
System.out.println("\nFile Transfer Done");
d.close();
echosocket.close();
}
}
- 35 -
Msc I.T Part I Advanced Computer
Networks
Practical 11
- 36 -
Msc I.T Part I Advanced Computer
Networks
Server Program:
import java.io.*;
import java.net.*;
remoteOut.println((s = userIn.readLine()));
if(s.equals("bye"))
break;
}
System.out.println("Shutting Server");
remoteIn.close();
remoteOut.close();
userIn.close();
clientSocket.close();
server.close();
}
catch(Exception e)
{
System.out.println(e);
}
- 37 -
Msc I.T Part I Advanced Computer
Networks
Client Program:
import java.io.*;
import java.net.*;
- 38 -
Msc I.T Part I Advanced Computer
Networks
remoteIn.close();
remoteOut.close();
userIn.close();
clientSocket.close();
}
catch (Exception e) { System.out.println(e); }
}
public static void main(String[] args)
{
try
{
new ChatClient();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
- 39 -
Msc I.T Part I Advanced Computer
Networks
- 40 -