CH - En.u4cse19101 - CN Lab 2
CH - En.u4cse19101 - CN Lab 2
EXPERIMENT -2
IMPLEMENTATION OF SOCKET PROGRAMMING
ALGORITHM:
This program is a basic one-way Client and server set up where a client connects and
sends a message to the server and server displays the messages using socket
connection
• Start
• Import all required packages
• Create a class Server
• Create a socket class and ServerSocket class which are required for
connection-oriented socket programming.
• Instance of ServerSocket class is created to create the server
application. The accept() method waits for the client server to respond.
Instance of Socket is returned if client connects to the correct port
number.
• The ServerSocket class can be used to create a server socket.
ServerSocket establishes communication with the clients.
• Create a client class
• Instance of Socket class is created to create the client application. The
IP address or hostname of the Server and a port number are passed as
parameters
• Now, execute server program and then client program
• Once client is connected whatever we type in console of client program
will be displayed in server console
PROGRAM:
SERVER CODE:
package socket;
import java.net.*;
import java.io.*;
public class Server{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
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.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
CLIENT CODE:
package socket;
import java.net.*;
import java.io.*;
public class Client{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",5236);
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")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}
}
OUTPUT:
Client Console:
Server console:
RESULT:
Thus, both the client and server exchange data using TCP socket programming.