Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Programs Using TCP Sockets (Like Date and Time Server & Client, Echo Server & Client, E.T.C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

1.

Programs using TCP Sockets (like date and time server & client,
echo server & client, e.t.c
EX.NO: 1a. PROGRAM USING TCP SOCKETS DATE AND TIME SERVER

AIM:

To implement date and time display from client to server using TCP Sockets

DESCRIPTION:
TCP Server gets the system date and time and opens the server socket to read the
client details. Clients end its address to the server. Then client receives the date and time from
server to display. TCP socket server client connection is opened for communication. After the
date time is displayed the server client connection is closed with its respective streams to be
closed.

ALGORITHM:

Server

1. Create a server socket and bind it to port.


2. Listen for new connection and when a connection arrives, accept it.
3. Send server’s date and time to the client.
4. Read client’s IP address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.

Client

1. Create a client socket and connect it to the server’s port number.


2. Retrieve its own IP address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.

PROGRAM:

//TCP Date Server--tcpdateserver.java


import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
{
public static void main(String arg[])
{
ServerSocket ss = null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{ ss = new ServerSocket(4444);
System.out.println("Press Ctrl+C to quit");|
while(true)
{
cs = ss.accept();
ps = new PrintStream(cs.getOutputStream());
Date d = new Date(); ps.println(d);
dis = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet = dis.readLine();
System.out.println("Client System/IP address is :"+ inet);
ps.close();
dis.close();
}
}
catch(IOException e)
{
System.out.println("The exception is :" + e);
}
}
}
// TCP Date Client--tcpdateclient.java
import java.net.*;
import java.io.*;
class tcpdateclient
{
public static void main (String args[])
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia = InetAddress.getLocalHost();
if (args.length == 0)
soc = new Socket(InetAddress.getLocalHost(),4444);
else
soc = new Socket(InetAddress.getByName(args[0]),4444);
dis = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("The date/time on server is : " +sdate);
ps = new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close(); catch(IOException e)
{
System.out.println("THE EXCEPTION is :" + e);
}
}
}

OUTPUT

Server:
$ javac tcpdateserver.java
$ java tcpdateserver
Press Ctrl+C to quit
Client System/IP address is : localhost.localdomain/127.0.0.1
Client System/IP address is : localhost.localdomain/127.0.0.1
Client:
$ javac tcpdateclient.java
$ java tcpdateclient
The date/time on server is: Wed Jul 06 07:12:03 GMT 2011

Every time when a client connects to the server, server’s date/time will be returned to
the client for synchronization.

RESULT

Thus the program for implementing to display date and time from client to server
using TCP Sockets was executed successfully and output verified using various samples.
EX.NO: 1b. IMPLEMENTATION OF CLIENT-SERVER COMMUNICATION
USING TCP

AIM:

To implement a chat server and client in java using TCP sockets

DESCRIPTION:
TCP Clients sends request to server and server will receives the request and response
with acknowledgement. Every time client communicates with server and receives response
from it.

ALGORITHM:

Server

1. Create a server socket and bind it to port..


2. Listen for new connection and when a connection arrives, accept it..
3. Read Client's message and display it.
4. Get a message from user and send it to client.
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams.
7. Close the server and client socket
8. Stop.

Client

1. Create a client socket and connect it to the server’s port number.


2. Get a message from user and send it to server
3. Read server's response and display it.
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket.
7. Stop.

PROGRAM:

//Server.java
import java.io.*;
import java.net.*;
class Server {
public static void main(string arg[]) {
string = "Networks Lab";
try { ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}

catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
//Client.java
import java.io.*;
import java.net.*;
class Client{
public static void main(String args[]) {
try{
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine());
System.out.print("'\n");
n.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}

OUTPUT

Server:
$ javac Server.java
$ java Server
Server started
Client connected
Cilent
$ javac Client.java
$ java Client

RESULT

Thus both the client and server exchange data using TCP socket programming.
EX.NO: 1c. IMPLEMENTATION OF TCP/IP ECHO

AIM:

To implementation of echo client server using TCP/IP

DESCRIPTION:
TCP Server gets the message and opens the server socket to read the client details.
Client send its address to the server. Then client receives the message from the server to
display

ALGORITHM:

Server

1. Create a server socket and bind it to port.


2. Listen for new connection and when a connection arrives, accept it.
3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close all streams.
7. Close the server socket.
8. Stop

Client
1. Create a client socket and connect it to the server‟s port number.
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.
9. Stop

PROGRAM:

//TCP Date Server--tcpdateserver.java


import java.net.*;
import java.io.*;
public class tcpechoserver
{
public static void main(String arg[])throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;
OutputStreamWriter toClient = null;
Socket client = null;
try
{
sock = new ServerSocket(4000); System.out.println("Server Ready");
client = sock.accept(); System.out.println("Client Connected");
fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
//TCP Echo Client--tcpechoclient.java
import java.net.*;
import java.io.*;
public class tcpechoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),4000);
else
sock = new Socket(InetAddress.getByName(args[0]),4000);
fromServer = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),true);
String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{
System.out.print("Enter msg to server : ");
Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye"); break;
}
else
toServer.println(Usrmsg);
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}

OUTPUT

Server:
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready Client Connected Client [ hello ]
Client [ how are you ] Client [ i am fine ] Client [ ok ]
Client Disconnected
Client:
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye

RESULT

Thus data from client to server is echoed back to the client to check reliability/noise level of
the channel
2. Programs using UDP Sockets

EX.NO: 2.a. PROGRAM USING UDP SOCKET UDP CHAT


SERVER/CLIENT

AIM
To implement a chat server and client in java using UDP sockets.

DESCRIPTION:
UDP is a connectionless protocol and the socket is created for client and
server to transfer the data. Socket connection is achieved using the port number.
Domain Name System is the naming convention that divides the Internet into logical
domains identified in Internet Protocol version 4 (IPv4) as a 32-bit portion of the total
address.

ALGORITHM:
Server
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to client port.
3. Create a datagram packet to receive client message.
4. Wait for client's data and accept it.
5. Read Client's message.
6. Get data from user.
7. Create a datagram packet and send message through server
port.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop.

Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip addr
and client port.
5. Create a datagram packet to receive server message.
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
9. Stop.
PROGRAM

// UDP Chat Server--udpchatserver.java


import java.io.*;
mport java.net.*;
class udpchatserver
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
DatagramSocket SrvSoc = new DatagramSocket(clientport);
byte[] SData = new byte[1024];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server Ready");
while (true)
{
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,RData.length);
SrvSoc.receive(RPack);
String Text = new String(RPack.getData());
if (Text.trim().length() == 0)
break;
System.out.println("\nFrom Client <<< " + Text );
System.out.print("Msg to Cleint : " );
String srvmsg = br.readLine();
InetAddress IPAddr = RPack.getAddress();
SData = srvmsg.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length,IPAddr,
serverport);
SrvSoc.send(SPack);
}
System.out.println("\nClient Quits\n");
SrvSoc.close();
}
}
// UDP Chat Client--udpchatclient.java
import java.io.*;
import java.net.*;
class udpchatclient
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
DatagramSocket CliSoc = new DatagramSocket(serverport);
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost();
else
IPAddr = InetAddress.getByName(args[0]);
byte[] SData = new byte[1024];
System.out.println("Press Enter without text to quit");
while (true)
{
System.out.print("\nEnter text for server : ");
Text = br.readLine();
SData = Text.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr,
clientport );
CliSoc.send(SPack);
if (Text.trim().length() == 0)
break;
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,RData.length);
CliSoc.receive(RPack);
String Echo = new String(RPack.getData());
Echo = Echo.trim();
System.out.println("From Server <<< " + Echo);
}
CliSoc.close();
}
}

OUTPUT
Server
$ javac udpchatserver.java
$ java udpchatserver
Server Ready
From Client <<< are u the SERVER
Msg to Cleint : yes
From Client <<< what do u have to serve
Msg to Cleint : no eatables
Client Quits
Client
$ javac udpchatclient.java$ java udpchatclient
Press Enter without text to quit
Enter text for server : are u the SERVER
From Server <<< yes
Enter text for server : what do u have to serve
From Server <<< no eatables
Enter text for server : Ok

RESULT
Thus both the client and server exchange data using UDP sockets.
Ex.No:2.b DNS SERVER TO RESOLVE A GIVEN HOST NAME

AIM:
To develop a client that contacts a given DNS server to resolve a given hostname.

DESCRIPTION:
Get the host name to be resolve using gethostname()
Check the host name using nslookup
Print the IP address, host name, Address length and Address type.
List the addresses stored in lookup

ALGORITHM

Step 1. Find the host name by using gethostbyname()


Step 2. The host name is followed by the list of alias names
Step 3. Pointer points to the array of pointers to the individual address
Step 4. For each address call the inet_ntop() and print the returned string

PROGRAM

#include<stdio.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<netinet/in.h>
int main(int argc,char**argv)
{
char h_name;
int h_type;
struct hostent *host;
struct in_addr h_addr;
if(argc!=2)
{
fprintf(stderr,"USAGE:nslookup\n");
}
if((host=gethostbyname(argv[1]))==NULL)
{
fprintf(stderr,"(mini)nslookup failed on %s\n",argv[1]);
}
h_addr.s_addr=*((unsigned long*)host->h_addr_list[0]);
printf("\n IP ADDRESS=%s\n",inet_ntoa(h_addr));
printf("\n HOST NAME=%s\n",host->h_name);
printf("\nADDRESS LENGTH =%d\n",host->h_length);
printf("\nADDRESS TYPE=%d\n",host->h_addrtype);
printf("\nLIST OF ADDRESS=%s\n",inet_ntoa(h_addr_list[0]));
}

OUTPUT
[it28@localhost ~]$ vi dns.c
[it28@localhost ~]$ cc dns.c
[it28@localhost ~]$ ./a.out 90.0.0.36
IP ADDRESS=90.0.0.36
HOST NAME=90.0.0.36
ADDRESS LENGTH =4
ADDRESS TYPE=2
LIST OF ADDRESS=90.0.0.36

RESULT

Hence the program to develop a client that contacts a given DNS server to resolve a
given host name is executed successfully
EX NO: 2.c UDP DNS SERVER/CLIENT
AIM:

To implement a DNS server and client in java using UDP sockets.

DESCRIPTION

DNS stands for domain name system. unique name of the host is identified with its IP
address through server client communication.

ALGORITHM:

Server

1. Create an array of hosts and its ip address in another array


2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop

Client

1. Create a datagram socket


2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message
5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop

PROGRAM

// UDP DNS Server -- udpdnsserver.java


import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim()
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return-1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140",
"69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}

//UDP DNS Client -- udpdnsclient.java

import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close(); }}

OUTPUT

Server
$ javac udpdnsserver.java
$ java udpdnsserve
Press Ctrl + C to Quit
Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com

Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found
RESULT

Thus domain name requests by the client are resolved into their respective logical
address using lookup method

You might also like