Anda di halaman 1dari 36

B.Tech.

(CSE)Fifth Semester
COMPUTER NETWORKS LAB
Code: EURCS 511
Credits: 2 Hours: 3 per week

Category: CE
Department: CSE

1. Write a program to
a. Print the IP address of a www.yahoo.com
b. Print the url of 205.163.22.104
c. Print all the addresses of www.apple.com
d. Print the IP address of the local machine
e. Print the hostname of the local machine
2. Write a program to Identify the well known ports on a Remote System
By trying to listen to the various well known ports by opening client connections. If the
exception does not occur then the remote port is active else the remote port is inactive.
3. Given a URL, write a program to print the parts of URL.
4. Write a program to display the sockets port and IP address.
5. Write a program to send & Receive data from DatagramPacket
6. Write a program for Multicast Sniffer
7. Write a program for Multicast sender
8. Write a program for a Chat Application
One-One: By opening socket connection and displaying what is written by one party to
the other.
Many-Many (Broad cast): Each client opens a socket connection to the chat server and
writes to the socket. Whatever is written by one party can be seen by all other parties.
9. Write a program for the Data Retrieval from a Remote Database
At the remote database a server listens for client connections. This server accepts SQL queries
from the client, executes it on the database and sends the response to the client.
10. Write a program for the Mail Client
POP Client : Gives the server name , user name and password retrieve the mails and
allow manipulation of mail box using POP commands.
SMTP Client: Gives the server name, send e-mail to the recipient using SMTP
commands- (Core Java 2 pg:163.)
11. Write a program for the Simulation of Telnet
Provide a user interface to contact well-known ports, so that client-server interaction can be seen
by the user.
12. Write a program for the Simple file transfer between two systems
By opening socket connection to our server on one system and sending a file from one system to
another.
13. Write a program for the TFTP-Client
To develop a TFTP client for file transfer. (Unix Network programming- Stevens)
14. Write a program for the HTTP-Server
Develop a HTTP server to implement the following commands GET, POST, HEAD, DELETE.
The server must handle multiple clients.
Reference Books:
1. Java Network Programming, Harold Orielly
2. An Introduction to Computer Networking, Kenneth C. Mansfield Jr and James
Antonakos Pearson Education Asia
Web Resource:
1. http://www.cafeaulait.org/books/jnp/javanetexamples/index.html

Lab Programs

1. Write a program to
a. Print the IP address of a www.yahoo.com / www.gitam.edu
Program:
www.yahoo.com
import java.net.*;
public class IPAddress
{
public static void main (String args[])
{
try
{
InetAddress addresses = InetAddress.getByName("www.yahoo.com");
System.out.println(addresses);
}
catch (UnknownHostException ex)
{
System.out.println("Could not find www.yahoo.com");
}
}
}
Output:
Could not find www.yahoo.com
Note: www.yahoo.com site could not find their address becauseit maintains separate DNS
www.gitam.edu
Program:
import java.net.*;
public class IPAddress
{
public static void main (String args[])
{
try
{
InetAddress addresses = InetAddress.getByName("www.gitam.edu");
System.out.println(addresses);
}
catch (UnknownHostException ex)
{
System.out.println("Could not find www.gitam.edu");
}
}

}
Output:
www.gitam.edu/192.168.23.9
(OR)
Program:
import java.net.*;
import java.io.*;
public class IPFinder
{
public static void main(String[] args) throws IOException
{
String host;
BufferedReader input =new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\nEnterhost name: ");
host = input.readLine();
try
{
InetAddress address = InetAddress.getByName(host);
System.out.println("IPaddress: " + address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Couldnot find " + host);
}
}
}
Output:

b. Print the url of 205.163.22.104


Program:
import java.net.*;
class URL
{
public static void main (String args[])
{
try
{
InetAddress address = InetAddress.getByName("192.168.23.9");
System.out.println(address.getHostName);
}
catch (UnknownHostException e)
{
System.out.println("Could not find 192.168.23.9");
}
}
}
Output:
cdl.gitam.edu
c. Print all the addresses of www.apple.com
Program:
import java.net.*;
class AllAddress {
public static void main (String args[]) {
try
{
InetAddress[] address = InetAddress.getAllByName("www.apple.com");
for (int i = 0; i < address.length; i++)
{
System.out.println(address[i]);
}
}
catch (UnknownHostException e)
{
System.out.println("could not find www.apple.com");
}
}
}
Output:
could not find www.apple.com
Note: www.apple.com site could not find their sites because it maintains separate DNS
Our proxy server not provided.

Print all the addresses of www.gitam.edu


Program:
import java.net.*;
class AllAddress {
public static void main (String args[]) {
try
{
InetAddress[] address = InetAddress.getAllByName("www.gitam.edu");
for (int i = 0; i < address.length; i++)
{
System.out.println(address[i]);
}
}
catch (UnknownHostException e)
{
System.out.println("could not find www.gitam.edu");
}
}
}
Output:
www.gitam.edu/192.168.23.9
Note: Our website having only one ip address
d. Print the IP address of the local machine
Program:
//Print the IP address of the local machine
import java.net.*;
class myAddress {
public static void main (String args[]) {
try {
// To get local machines IP address
InetAddress address = InetAddress.getLocalHost();
System.out.println("\n IP Address is: "+address);
}
catch (UnknownHostException e) {
System.out.println("Could not find this computer's address.");
}
}
}
Output:

IP Address is: padmaja-PC/172.17.248.89


e. Print the hostname of the local machine and hostname
Program:
//Print the IP address of the local machine & host name
import java.net.*;
class myAddress1 {
public static void main (String args[]) {
try {
// To get local machines IP address
InetAddress address = InetAddress.getLocalHost();
System.out.println("\n IP Address is: "+address);
// To get the local machines name
String s1=address.getHostName();
System.out.println("System name is: "+s1);
}
catch (UnknownHostException e) {
System.out.println("Could not find this computer's address.");
}
}
}
Output:
IP Address is: padmaja-PC/172.17.248.89
System name is: padmaja-PC
2. Write a program to Identify the well known ports on a Remote System
By trying to listen to the various well known ports by opening client connections. If the
exception does not occur then the remote port is active else the remote port is inactive.
Program:
import java.io.*;
import java.net.*;
public class wkports1{
public static void main(String args[]){
String host="localhost";
if(args.length>0) host=args[0];
for(int i=100;i<200;i++){
try{
Socket s=new Socket(host,i);

System.out.println("There is server on port : " +i+" of : "+host);


s.close();
}
catch(IOException ie){
}
}
}
}
Output:
There is server on port : 135 of : localhost
(OR)
import java.io.*;
import java.net.*;
public class wkports
{
public static void main(String args[]) throws Exception
{
InetAddress address=InetAddress.getLocalHost();
String host=address.getHostName();
/* String haddr=address.getHostAddress();
System.out.println("\n Host Name::"+host);
System.out.println("\n Host Address::"+haddr);

*/

for(int i=100;i<1024;i++)
{
Socket s=null;
try
{
s=new Socket((host),i);
System.out.println("Port: " + i + "Active");
}
catch(SocketException se)
{
}
catch(Exception e)
{
System.out.println("Error...");
}
}
}
}
Output:
Port: 135 Active
Port: 139 Active

Port: 445 Active


(OR)
Program:
import java.net.*;
import java.io.*;
public class PortScanner
{
public static void main(String[] args)
{
String host = "localhost";
if (args.length > 0)
{
host = args[0];
}
try
{
InetAddress theAddress = InetAddress.getByName(host);
for (int i = 1; i < 65536; i++)
{
Socket connection = null;
try
{
connection = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
}
catch (IOException ex)
{
// must not be a server on this port
}
finally
{
try
{
if (connection != null) connection.close();
}
catch (IOException ex) {}
}
} // end for
} // end try
catch (UnknownHostException ex)
{
System.err.println(ex);
}
} // end main
} // end PortScanner
Output:

Program:
import java.net.*;
import java.io.*;
public class LowPortScanner
{
public static void main(String[] args)
{
String host = "localhost";
if (args.length > 0)
{
host = args[0];
}
for (int i = 1; i < 1024; i++)
{
try
{
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
} // end try
catch (UnknownHostException ex)
{
System.err.println(ex);
break;
} // end catch
catch (IOException ex)
{
// must not be a server on this port
} / end catch
} // end for
} // end main
} // end PortScanner
Output:

3. Given a URL, write a program to print the parts of URL.


Program:
import java.net.*;
import java.io.*;

public class getURLParts {


public static void main(String args[]) {
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[0]);
System.out.println("The URL is " + u);
System.out.println("The protocol part is " + u.getProtocol());
System.out.println("The host part is " + u.getHost());
System.out.println("The port part is " + u.getPort());
System.out.println("The file part is " + u.getFile());
System.out.println("The ref part is " + u.getRef());
} // end try
catch (MalformedURLException e) {
System.err.println(args[0] + "is not a URL I understand.");
}
} // end for
} // end main
} // end getURLParts
Output:

(OR)
Program:
import java.net.*;
import java.io.*;
import java.lang.*;
import java.net.URL;
public class ParseURL {

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


URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
Output:

(OR)
Program:
import java.net.*;
import java.io.*;
import java.net.URL;
public class URLSplitter {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
System.out.println("The URL is " + u);
System.out.println("The scheme is " + u.getProtocol());
System.out.println("The user info is " + u.getUserInfo());
String host = u.getHost();

if (host != null) {
int atSign = host.indexOf('@');
if (atSign != -1) host = host.substring(atSign+1);
System.out.println("The host is " + host);
}
else {
System.out.println("The host is null.");
}
System.out.println("The port is " + u.getPort());
System.out.println("The path is " + u.getPath());
System.out.println("The ref is " + u.getRef());
System.out.println("The query string is " + u.getQuery());
} // end try
catch (MalformedURLException ex) {
System.err.println(args[i] + " is not a URL I understand.");
}
System.out.println();
} // end for
} // end main
} // end URLSplitter
Output:

4. Write a program to display the sockets port and IP address


Program:
import java.net.*;
import java.io.*;
public class SocketInfo
{
public static void main(String[] args)
{

for (int i = 0; i < args.length; i++)


{
try
{
Socket theSocket = new Socket(args[i], 80);
System.out.println("Connected to " + theSocket.getInetAddress()
+ " on port " + theSocket.getPort() + " from port "
+ theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
} // end try
catch (UnknownHostException e)
{
System.err.println("I can't find " + args[i]);
}
catch (SocketException e)
{
System.err.println("Could not connect to " + args[i]);
}
catch (IOException e)
{
System.err.println(e);
}
} // end for
} // end main
} // end SocketInfo
Output:

(OR)
//display socket InetAddress, port, localport and local address
import java.net.Socket;
public class MainClass {
public static void main(String[] args) throws Exception {
Socket theSocket = new Socket("192.168.23.9", 80);
System.out.println("Connected to " + theSocket.getInetAddress() + " on port "
+ theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of "

+ theSocket.getLocalAddress());
}
}
Output:

5. Write a program to send & Receive data from DatagramPacket


Program:
import java.net.*;
public class DatagramExample {
public static void main(String[] args) {
String s = "This is a test.";
byte[] data = s.getBytes( );
try {
InetAddress ia = InetAddress.getByName("www.gitam.edu");
int port = 7;
DatagramPacket dp= new DatagramPacket(data, data.length, ia, port);
System.out.println("This packet is addressed to "+ dp.getAddress() + " on port " + dp.getPort( ));
System.out.println("There are " + dp.getLength( ) + " bytes of data in the packet");
System.out.println(new String(dp.getData(), dp.getOffset(), dp.getLength( )));
}
catch (UnknownHostException e) {
System.err.println(e);
}
}
}
Output:

6. Write a program for Multicast Sniffer


Program:
import java.net.*;

import java.io.*;
public class MulticastSniffer
{
public static void main(String[] args)
{
InetAddress group = null;
int port = 0;
// read the address from the command line
try
{
group = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} // end try
catch (Exception ex)
{
// ArrayIndexOutOfBoundsException, NumberFormatException,
// or UnknownHostException
System.err.println("Usage: java MulticastSniffer multicast_address port");
System.exit(1);
}
MulticastSocket ms = null;
try
{
ms = new MulticastSocket(port);
ms.joinGroup(group);
byte[] buffer = new byte[50];
while (true)
{
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ms.receive(dp);
String s = new String(dp.getData( ));
System.out.println(s);
}
}
catch (IOException ex)
{
System.err.println(ex);
}
finally
{
if (ms != null)
{
try
{
ms.leaveGroup(group);
ms.close( );

}
catch (IOException ex) {}
}
}
}
}
7. Write a program for Multicast sender
Program:
import java.io.*;
public class MulticastSender
{
public static void main(String[] args)
{
InetAddress ia = null;
int port = 0;
byte ttl = (byte) 1;
try
{
ia = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
if (args.length > 2) ttl = (byte) Integer.parseInt(args[2]);
} // end try
catch (Exception ex)
{
System.err.println(ex);
System.err.println("Usage: java MulticastSender multicast_address port ttl");
System.exit(1);
} //end catch
byte[] data = "Here's some multicast data\r\n".getBytes( );
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
try
{
MulticastSocket ms = new MulticastSocket( );
ms.joinGroup(ia);
for (int i = 1; i <= 10; i++)
{
ms.send(dp, ttl);
} //end for
ms.leaveGroup(ia);
ms.close( );
} // end try
catch (SocketException ex)
{
System.err.println(ex);

} // end catch
catch (IOException ex)
{
System.err.println(ex);
} //end Catch
} // End main
} // End MulticastSender
How to execute the program:
Execute 6 & 7 programs
First open two command prompts
Compile & run MulticastSniffer program in one command prompt
javac MulticastSniffer.java
java MulticastSniffer 239.255.255.255.3000
Compile & run MulticastSender program in another command prompt separately
javac MulticastSender.java
java MulticastSender 239.255.255.255.3000
Then output shows in MulticastSniffer command prompt as Heres some multicast data is
printed 10 times

8. Write a program for a Chat Application


One-One: By opening socket connection and displaying what is written by one party
to the other.

Many-Many (Broad cast): Each client opens a socket connection to the chat server
and writes to the socket. Whatever is written by one party can be seen by all other
parties.

One-One:
Client side Program:
import java.io.*;
import java.net.*;
import java.lang.*;
public class chatclient1
{
public static void main(String args[])
throws IOException
{
Socket csoc = null;
String host;
if(args.length>0)
host=args[0];
else host="localhost";
PrintWriter pout=null;
BufferedReader bin=null;
try
{
csoc = new Socket(host,7);
pout = new PrintWriter(csoc.getOutputStream(),true);
bin = new BufferedReader(new InputStreamReader(csoc.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.println("unknown Host");
System.exit(1);
}
catch(IOException e){}
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String input;
while(true)
{
input = in.readLine();
pout.println(input);
String msg=bin.readLine();
System.out.println("Server: "+msg);
if(msg.equals("Bye")) break;
}
in.close();
pout.close();
bin.close();
csoc.close();
}
}
Server Side Program:

import java.io.*;
import java.net.*;
import java.lang.*;
public class chatserver
{
public static void main(String args[])
throws IOException
{
ServerSocket ssoc = null;
try{
ssoc = new ServerSocket(7);
}
catch(IOException e)
{
System.err.println("No Connection Established");
System.exit(1);
}
Socket csoc = null;
try
{
csoc=ssoc.accept();
}
catch(IOException e)
{
System.err.println("not Accepted");
System.exit(1);
}
PrintWriter pw = new PrintWriter(csoc.getOutputStream(),true);
BufferedReader
br = new BufferedReader(new
InputStreamReader(csoc.getInputStream()));
String inline,outline;
try
{
DataInputStream din= new DataInputStream(System.in);
while(true)
{
inline = br.readLine();
System.out.println("Client : "+inline);
outline=din.readLine();
pw.println(outline);
if(outline.equals("Bye")) break;
}
}
catch(IOException e)
{
System.err.println(e);
}
pw.close();
br.close();

ssoc.close();
csoc.close();
}
}
How to execute the program:
First open two command prompts
Compile Client side program in one command prompt
Compile Server side program in another command prompt separately
First run the serve side program then run the client side program
Send data from client to server and from server to client.

Many-Many (Broad cast):


Client side Program:
import java.net.*;
import java.io.*;

public class MmClient1


{
static Socket s=null;
static String name;
static DataInputStream dd;
public static void main(String args[])
{
try{
System.out.println("enter the name:");
dd=new DataInputStream(System.in);
name=dd.readLine();
}
catch(Exception e)
{
System.err.println(e);
}
try
{
s=new Socket("localhost",721); // ip address of the server
cliSend2 cs=new cliSend2(s);
cs.start();
ClRec2 cr=new ClRec2(s);
cr.start();
}
catch(Exception e)
{
System.err.println(e);
}
}
}
class cliSend2 extends Thread
{
Socket s;
static PrintWriter pw;
cliSend2(Socket s) throws Exception
{
this.s=s;
pw=new PrintWriter(s.getOutputStream(),true);
}
public void run()
{
while(true)
{
try
{
DataInputStream din=new DataInputStream(System.in);

String str1=din.readLine();
pw.println(" "+MmClient1.name+":"+str1);
}catch(Exception e)
{
System.err.println(e);
}
}
}
}
class ClRec2 extends Thread
{
Socket s;
static BufferedReader br;
ClRec2(Socket s) throws Exception
{
this.s=s;
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
}
public void run()
{
try
{
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
line=br.readLine();
}
}catch(Exception e)
{
System.err.println(e);
}
}
}
Server side Program:
import java.io.*;
import java.net.*;
public class MmServer1
{
static Socket s[]=new Socket[10];
static int count;
public static void main(String args[]) throws Exception
{
ServerSocket ss;
try
{
ss=new ServerSocket(721);
System.out.println("Server Running");
SrSend1 sr=new SrSend1();
sr.start();

while(true)
{
s[count]=ss.accept();
CliSend1 cs=new CliSend1(count);
cs.start();
count++;
}
}
catch(Exception e)
{
System.err.println(e);
}
}
}
class CliSend1 extends Thread
{
BufferedReader br;
PrintWriter pw;
Socket s;
String str;
int c;
CliSend1(int c)
{
// this.s=s;
this.c=c;
try
{
br=new BufferedReader(new
InputStreamReader((MmServer1.s[c]).getInputStream()));
}catch(Exception e)
{
System.err.println(e);
}
}
public void run()
{
while(true)
{
try
{
str=br.readLine();
System.out.println(str);
for(int i=0;i<MmServer1.count;i++)
{
if(i==c)
continue;
pw=new PrintWriter(MmServer1.s[i].getOutputStream(),true);
pw.println(str);
}
}catch(Exception e)
{
System.err.println(e);
}

}
}
}
class SrSend1 extends Thread
{
BufferedReader br;
String str;
PrintWriter pw;
SrSend1() throws Exception
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public void run()
{
while(true)
{
try
{
str=br.readLine();
for(int i=0;i<MmServer1.count;i++)
{
pw=new PrintWriter(MmServer1.s[i].getOutputStream(),true);
pw.println("Server:"+str);
}
}catch(Exception e)
{
System.err.println(e);
}
}
}
}
How to execute the program:
First open three command prompts
Compile Client side program in two command prompt
Compile Server side program in one command prompt separately
First run the serve side program
then run the client side program give a name of the client as x
next run the another client side program give a name of the client as y
Send data from one client that data visible in server side and other client side
Send data from server that data visible in both client sides
Send data from another client that data visible in server side and other client side

12. Write a program for the Simple file transfer between two systems

By opening socket connection to our server on one system and sending a file from one
system to another.
Client side Program:
import java.net.*;
import java.io.*;
public class ftpclient{
public static void main(String args[]){
Socket s;
BufferedReader in,br;
PrintWriter pw;
String spath,dpath;
FileOutputStream fos;
int c;
try{
s=new Socket("localhost",1111);
in=new BufferedReader(new InputStreamReader(System.in));
br=new BufferedReader(new InputStreamReader (s.getInputStream()));
pw=new PrintWriter(s.getOutputStream(),true);
System.out.println("\n Enter source file to be copied");
spath=in.readLine();
System.out.println("\n Enter Destination Path to Transfer:");
dpath=in.readLine();
fos=new FileOutputStream(dpath);
pw.println(spath);
while((c=br.read())!=-1){
fos.write((char)c);
fos.flush();
}
System.out.println("File Transfer Completed");
}
catch(Exception e){
System.out.println(e);
}
}
}
Server side Program:
import java.net.*;
import java.io.*;
public class ftpserver{
public static void main(String args[]){
Socket s;
ServerSocket server;
BufferedReader br;
PrintWriter pw;
String filename;
FileInputStream fis;
int c;
try{
server=new ServerSocket(1111);

System.out.println("Server Waiting for Connection:\n");


s=server.accept();
System.out.println("Connection Established:\n");
br=new BufferedReader(new InputStreamReader (s.getInputStream()));
pw=new PrintWriter(s.getOutputStream());
filename=br.readLine();
fis=new FileInputStream(filename);
while((c=fis.read())!=-1){
pw.print((char)c);
pw.flush();
}
System.out.println(filename + "copied to destination");
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
How to execute the program:
First open two command prompts
Compile and run Server side program in one command prompt
Compile and run Client side program in another window
Enter source file to be copied
Enter new name to save that data
That new file automatically created and copied and located in same location of source program

13. Write a program for the TFTP-Client. To develop a TFTP client for file transfer.

Client side Program:


import java.io.*;
import java.net.*;
import java.lang.*;
public class tftpc
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(1501);
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter file to save");
String file=input.readLine();
FileOutputStream fos=new FileOutputStream(file);
System.out.println("enter file to trans");
file=input.readLine();
byte s[]=new byte[file.length()];
s=file.getBytes();
String data=null;
ds.send(new DatagramPacket(s,s.length,InetAddress.getLocalHost(),1500));
while(true)
{
s=new byte[1024];
DatagramPacket dp=new DatagramPacket(s,1024);
ds.receive(dp);
data=new String(dp.getData(),0,dp.getLength());
if(data.equals("***")) break;
fos.write(data.getBytes());
}
fos.close();
ds.close();
}
}
Server side Program:
import java.io.*;
import java.net.*;
import java.lang.*;
public class tftps
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(1500);
byte s[]=new byte[1024];
DatagramPacket dp=new DatagramPacket(s,1024);
ds.receive(dp);
System.out.println("Client Connected");
String data=new String(dp.getData(),0,dp.getLength());
int count=0;
System.out.println("Transferred");
FileInputStream fs=new FileInputStream(data);
while(fs.available()!=0)

{
if(fs.available()<1024) count=fs.available();
else count=1024;
s=new byte[count];
fs.read(s);
dp=new DatagramPacket(s,s.length,InetAddress.getLocalHost(),1501);
ds.send(dp);
}
fs.close();
s=new byte[3];
s="***".getBytes();
ds.send(new DatagramPacket(s,s.length,InetAddress.getLocalHost(),1501));
ds.close();
}
}
How to execute the program:
First open two command prompts
Compile and run Server side program in one command prompt
Compile and run Client side program in another window
Enter file to be save (new name)
Enter file to transfer (existing file)
That new file automatically created and copied and located in same location of source program

14. Write a program for the HTTP-Server


Develop a HTTP server to implement the following commands GET, POST, HEAD,
DELETE. The server must handle multiple clients.
Client side Program:
import java.io.*;
import java.net.*;

import java.lang.*;
public class httpc{
public static void main(String args[]) throws Exception{
Socket soc=new Socket ("localhost",1111);
BufferedReader
br=new
BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter pw=new PrintWriter(soc.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server is connected\n");
int ch;
do{
System.out.println("commands");
System.out.println("\n 1.head \n 2.post \n 3.get \n 4.delete \n other-exit");
System.out.println("Enter ur choice");
ch=Integer.parseInt(in.readLine());
byte line[]=null;
String file;
switch(ch){
case 1:
pw.println("1");
file = in.readLine();
pw.println(file);
String type=br.readLine();
String length= br.readLine();
System.out.println("File:"+file+" In type:"+type+"
In length:"+length);
break;
case 2:
pw.println("2");
System.out.println("Enter text to post");
file = in.readLine();
pw.println(file);
System.out.println("Text is posted.");
break;
case 3:
pw.println("3");
System.out.println("enter file name to get : ");
file =in.readLine();
pw.println(file);
System.out.println("enter file name to save : ");
file =in.readLine();
FileOutputStream fs = new FileOutputStream(file);
while(true){
String s = br.readLine();
if(s.equals("***"))
break;
int count =s.length();
if(count<1024)
line=new byte[1024];
line=s.getBytes();
fs.write(line);
}

fs.close();
System.out.println("\n File transfer Succesful");
break;
case 4:
pw.println("4");
System.out.println("enter file name to delete: ");
file=in.readLine();
pw.println(file);
System.out.println("Given file deleted:");
break;
default:
pw.println("5");
System.exit(0);
}
}while(ch>0&&ch<5);
soc.close();
}
}
Server side Program:
import java .io.*;
import java.net.*;
import java.lang.*;
public class https{
public static void main(String args[]) throws Exception {
ServerSocket ssoc = new ServerSocket(1111);
System.out.println("Server waiting for client");
Socket soc=ssoc.accept();
System.out.println("client connected to the Server:\n");
BufferedReader
br=new
BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter pw=new PrintWriter(soc.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int ch;
do{
ch=Integer.parseInt(br.readLine());
String file;
byte line[]=null;
File f;
switch(ch) {
case 1:
System.out.println("1.Head");
file =br.readLine();
f=new File(file) ;
int index = file.lastIndexOf(".");
String type = file.substring(index+1);
pw.println(type);
long length=f.length();
pw.println(length);
break;
case 2:
System.out.println("2.Post");

file =br.readLine();
System.out.println("Message from Client : \n");
System.out.println(file);
break;
case 3:
System.out.println("3.Get");
file =br.readLine();
FileInputStream fs = new FileInputStream(file);
while(fs.available()!=0){
if(fs.available()<1024)
line =new byte[fs.available()];
else line =new byte[1024];
fs.read(line);
file = new String (line);
pw.println(file);
}
pw.println("***");
fs.close();
break;
case 4:
System.out.println("4.Delete");
file =br.readLine();
f=new File(file) ;
f.delete();
break;
case 5 :
System.out.println("Other-Exit");
System.exit(0);
}
}while(ch>0&&ch<5);
soc.close();
ssoc.close();
}
}
How to execute the program:
First open two command prompts
Compile and run Server side program in one command prompt
Compile and run Client side program in another window
Commands:
1.head
2.post
3.get
4.delete
other-exit
1.Head means Whatever file is entered complete information is visible like as file name, flie
type, file length
2.post means whatever message is given by you that message is visible in server side
3.get means any file is transferred into new file
4.delete means any existing file is to be deleted

The server must handle multiple clients


Client program same
Server side Program:
import java .io.*;

import java.net.*;
import java.lang.*;
public class mhttps extends Thread{
static Socket sock[]=new Socket[10];
int c;
public mhttps(int n)
{
c=n;
}
public static void main (String args[]) throws Exception {
int n=0;
ServerSocket ssoc=new ServerSocket(1111);
do {
System.out.println("Server waiting for client");
sock[n]=ssoc.accept();
new mhttps(n).start();
System.out.println("client "+n+" connected to the Server:\n");
n++;
}while(n<10);
ssoc.close();
}
public void run() {
try{
Socket soc=mhttps.sock[c];
BufferedReader br=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter pw=new PrintWriter(soc.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int ch;
do{
ch=Integer.parseInt(br.readLine());
String file;
byte line[]=null;
File f;
switch(ch) {
case 1:
System.out.println("1.Head");
file =br.readLine();
f=new File(file) ;
int index = file.lastIndexOf(".");
String type = file.substring(index+1);
pw.println(type);
long length=f.length();
pw.println(length);
break;
case 2:
System.out.println("2.Post");
file =br.readLine();
System.out.println("Message from Client : "+c );
System.out.println(file);
break;
case 3:
System.out.println("3.Get");

file =br.readLine();
FileInputStream fs = new FileInputStream(file);
while(fs.available()!=0){
if(fs.available()<1024)
line =new byte[fs.available()];
else line =new byte[1024];
fs.read(line);
file = new String (line);
pw.println(file);
}
pw.println("***");
fs.close();
break;
case 4:
System.out.println("4.Delete");
file =br.readLine();
f=new File(file) ;
f.delete();
break;
case 5 :
System.out.println("Other-Exit");
soc.close();
Thread.currentThread().stop();
}
}while(ch>0&&ch<5);
}
catch(IOException e){}
}
}
How to execute the program:
First open two or three command prompts
Compile and run Server side program in one command prompt
Compile and run Client side program in another window as first client
Compile and run Client side program in another window as second client

Anda mungkin juga menyukai