0% found this document useful (0 votes)
2K views15 pages

Create A Socket For HTTP For Web Page Upload and Download

The document discusses creating a socket for HTTP communication to enable web page upload and download. It provides code for a client and server application that can transfer an image file from the client to the server. The client code opens a socket connection, reads an image file, sends it to the server, and closes the connection. The server code accepts the connection from the client, receives the image data, writes it back to a file, and displays the image. The document also discusses simulating the PING and TRACEROUTE commands by executing them as system commands from within Java code and outputting the results.

Uploaded by

Ashish mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views15 pages

Create A Socket For HTTP For Web Page Upload and Download

The document discusses creating a socket for HTTP communication to enable web page upload and download. It provides code for a client and server application that can transfer an image file from the client to the server. The client code opens a socket connection, reads an image file, sends it to the server, and closes the connection. The server code accepts the connection from the client, receives the image data, writes it back to a file, and displays the image. The document also discusses simulating the PING and TRACEROUTE commands by executing them as system commands from within Java code and outputting the results.

Uploaded by

Ashish mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Q1.

Create a socket for HTTP for web page upload and download

CODE:

import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import
java.io.File;
import java.io.IOException; import javax.imageio.ImageIO;
public class client
{
public static void main(String args[]) throws Exception{ Socket soc;

BufferedImage img = null;


soc=new Socket("localhost",4000);

System.out.println("Client is running. ");


try {

System.out.println("Reading image from disk. ");

img = ImageIO.read(new File("ashish.jpg")); ByteArrayOutputStream baos = new


ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray(); baos.close();

System.out.println("Sending image to server. ");


OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);

dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class server
{
public static void main(String args[]) throws Exception{
ServerSocket server=null;

Socket socket;

server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept(); System.out.println("Client connected.");
InputStream in =socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];

dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);

f.pack();
f.setVisible(true);
}
}

Q2 Write a code simulating PING and TRACEROUTE commands.

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class traceroutecmd


{

public static void runSystemCommand(String command)

try

Process p = Runtime.getRuntime().exec(command);

BufferedReader inputStream = new BufferedReader(

new InputStreamReader(p.getInputStream()));

String s = "";

while ((s = inputStream.readLine()) != null)

System.out.println(s);

catch (Exception e)

public static void main(String[] args)

// String ip = "www.google.co.in";

// String ip = "127.0.0.1";

String ip = "www.drranurekha.com";

runSystemCommand("tracert " + ip);

OUTPUT:
>javac traceroutecmd.java

>java traceroutecmd

Tracing route to drranurekha.com [160.153.137.167] over a maximum of 30 hops:

1 <1 ms <1 ms <1 ms 10.0.15.1


2 <1 ms <1 ms <1 ms 10.0.0.15
3 1 ms 1 ms 1 ms 210.212.247.209
4 2 ms 1 ms 1 ms 172.24.75.102
5 * * 21 ms 218.248.235.217
6 * * 12 ms 218.248.235.218
7 21 ms 21 ms 21 ms 121.244.37.253.static.chennai.vsnl.net.in [121.244.37.253]
8 * * * Request timed out.
9 49 ms 49 ms 49 ms 172.25.81.134
10 50 ms 50 ms 70 ms ix-ae-0-4.tcore1.mlv-mumbai.as6453.net [180.87.38.5]
11 165 ms 165 ms 165 ms if-ae-9-5.tcore1.wyn-marseille.as6453.net [80.231.217.17]
12 172 ms 171 ms 171 ms if-ae-8-1600.tcore1.pye-paris.as6453.net [80.231.217.6]
13 171 ms 171 ms 171 ms if-ae-15-2.tcore1.av2-amsterdam.as6453.net
[195.219.194.145]
14 175 ms 175 ms 175 ms 195.219.194.2
15 171 ms 170 ms 170 ms po72.bbsa0201-01.bbn.mgmt.ams1.gdg [188.121.33.74]
16 170 ms 169 ms 169 ms 10.241.131.203
17 175 ms 175 ms 175 ms 10.253.1.1
18 166 ms 166 ms 166 ms 10.253.130.9
19 173 ms 173 ms 173 ms 10.253.130.3
20 169 ms 169 ms 169 ms 10.253.130.5
21 169 ms 169 ms 169 ms ip-160-153-137-167.ip.secureserver.net [160.153.137.167]

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class pingcmd


{
public static void runSystemCommand(String command)
{
try
{
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));

String s = "";
while ((s = inputStream.readLine()) != null)
System.out.println(s);
}
catch (Exception e)
{
}
}
public static void main(String[] args)
{

String ip = "www.drranurekha.com";
runSystemCommand("ping " + ip);
}
}

Sample Output:

>javac pingcmd.java

>java pingcmd

Pinging drranurekha.com [160.153.137.167] with 32 bytes of data:


Reply from 160.153.137.167: bytes=32 time=167ms TTL=45
Reply from 160.153.137.167: bytes=32 time=167ms TTL=45
Reply from 160.153.137.167: bytes=32 time=167ms TTL=45
Reply from 160.153.137.167: bytes=32 time=167ms TTL=45

Ping statistics for 160.153.137.167:


Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 167ms, Maximum = 167ms, Average = 167ms
>

Q3. Study and implement model for Socket Programming and Client – Server model.
SERVER.JAVA:

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Client.java

15. import java.io.*;


16. import java.net.*;
17. public class MyClient {
18. public static void main(String[] args) {
19. try{
20. Socket s=new Socket("localhost",6666);
21. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
22. dout.writeUTF("Hello Server");
23. dout.flush();
24. dout.close();
25. s.close();
26. }catch(Exception e){System.out.println(e);}
27. }
28. }

Q4. Study of Network simulator (NS).and Simulation of Congestion Control


Algorithms using NS.

What is congestion?
A state occurring in network layer when the message traffic is so heavy that it slows down
network response time.
Effects of Congestion

 As delay increases, performance decreases.


 If delay increases, retransmission occurs, making situation worse.
Congestion control algorithms

 Leaky Bucket Algorithm


Let us consider an example to understand
Imagine a bucket with a small hole in the bottom.No matter at what rate water enters the
bucket, the outflow is at constant rate.When the bucket is full with water additional water
entering spills over the sides and is lost.

Similarly, each network interface contains a leaky bucket and the following steps are
involved in leaky bucket algorithm:

29. When host wants to send packet, packet is thrown into the bucket.
30. The bucket leaks at a constant rate, meaning the network interface transmits packets at a
constant rate.
31. Bursty traffic is converted to a uniform traffic by the leaky bucket.
32. In practice the bucket is a finite queue that outputs at a finite rate.
 Token bucket Algorithm
Need of token bucket Algorithm:-

The leaky bucket algorithm enforces output pattern at the average rate, no matter how bursty the
traffic is. So in order to deal with the bursty traffic we need a flexible algorithm so that the data is not
lost. One such algorithm is token bucket algorithm.

Steps of this algorithm can be described as follows:

33. In regular intervals tokens are thrown into the bucket. ƒ


34. The bucket has a maximum capacity. ƒ
35. If there is a ready packet, a token is removed from the bucket, and the packet is sent.
36. If there is no token in the bucket, the packet cannot be sent.

Let’s understand with an example,

In figure (A) we see a bucket holding three tokens, with five packets waiting to be transmitted. For a
packet to be transmitted, it must capture and destroy one token. In figure (B) We see that three of the
five packets have gotten through, but the other two are stuck waiting for more tokens to be
generated.

Ways in which token bucket is superior to leaky bucket:


The leaky bucket algorithm controls the rate at which the packets are introduced in the network, but
it is very conservative in nature. Some flexibility is introduced in the token bucket algorithm. In the
token bucket, algorithm tokens are generated at each tick (up to a certain limit). For an incoming
packet to be transmitted, it must capture a token and the transmission takes place at the same rate.
Hence some of the busty packets are transmitted at the same rate if tokens are available and thus
introduces some amount of flexibility in the system.

Q5. create Echo client and echo server for A. Chat B. File Transfer

A.CHAT:
Server:

import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[]) throws Exception,UnknownHostException{
ServerSocket ss=new ServerSocket(8088);
Socket s=ss.accept();;
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(str!="stop")
{
System.out.println("Waiting for client's Reply...");
str=din.readUTF();
System.out.println("Client: "+str);
System.out.println("Enter Message:");
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}

A.CHAT:
Client

import java.net.*;

import java.io.*;

public class Client {


public static void main(String[] args) throws Exception {

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

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

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

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

String str="",str2="";

while(!str.equals("stop")){

System.out.println("\nEnter Response: ");

str=br.readLine();

dout.writeUTF(str);

dout.flush();

System.out.println("Waiting for Server's Reply...");

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

FILE TRANSFER:

# server.py

import socket # Import socket module

port = 60000 # Reserve a port for your service.

s = socket.socket() # Create a socket object

host = socket.gethostname() # Get local machine name

s.bind((host, port)) # Bind to the port


s.listen(5) # Now wait for client connection.

print 'Server listening....'

while True:

conn, addr = s.accept() # Establish connection with client.

print 'Got connection from', addr

data = conn.recv(1024)

print('Server received', repr(data))

filename='mytext.txt'

f = open(filename,'rb')

l = f.read(1024)

while (l):

conn.send(l)

print('Sent ',repr(l))

l = f.read(1024)

f.close()

print('Done sending')

conn.send('Thank you for connecting')

conn.close()

# client.py

import socket # Import socket module

s = socket.socket() # Create a socket object

host = socket.gethostname() # Get local machine name


port = 60000 # Reserve a port for your service.

s.connect((host, port))

s.send("Hello server!")

with open('received_file', 'wb') as f:

print 'file opened'

while True:

print('receiving data...')

data = s.recv(1024)

print('data=%s', (data))

if not data:

break

# write data to a file

f.write(data)

f.close()

print('Successfully get the file')

s.close()

print('connection closed')

Output on a local server:

Server listening....

Got connection from ('192.168.56.10', 62854)

('Server received', "'Hello server!'")

('Sent ', "'1 1234567890\\n

...

('Sent ', "'4567890\\n105

...

('Sent ', "'300 1234567890\\n'")


Done sending

Output on a local client:

file opened

receiving data...

data=1 1234567890

2 1234567890

...

103 1234567890

104 123

receiving data...

data=4567890

105 1234567890

106 1234567890

...

299 1234567890

receiving data...

data=300 1234567890

Thank you for connecting

receiving data...

data=

Successfully get the file

connection closed

You might also like