Problem Definition: Write a program in Java to implement Socket Programming.
P.S. Here, both the programs viz., Server & Client needs to be executed simultaneously on different Java Windows (2 Terminals).
It’s the one-to-one message provision, where after each message from the Client Server has to respond and vice verse.
/*Server Program*/
import java.util.*;
import java.io.*;
import java.net.*;
public class server
{
public static void main(String args[])
{
try
{
//Create Server Socket
ServerSocket server=new ServerSocket(1794);
//Connection with client
Socket client=server.accept();
Scanner sc=new Scanner(System.in);
//Object of Scanner to read from Server(Receive Data)
Scanner in=new Scanner(client.getInputStream());
//Object of PrintWriter to write on to the Server(Send Data)
PrintWriter out=new PrintWriter(client.getOutputStream(),true);//true means autoflush enabled no need to flush everytime(While Sending Data)
String s=””;
System.out.println(“Client Connected”+”\n”);
do
{
//Receive Data
s=in.nextLine();
System.out.println(“Client:”+s);
System.out.print(“Server:”);
//accept input from user
s=sc.nextLine();
//send data
out.println(s);
}while(!s.equalsIgnoreCase(“bye”));
server.close();//close the socket
}
catch(Exception e)
{
}
}
}
/*Client Program*/
import java.util.*;
import java.io.*;
import java.net.*;
public class client
{
public static void main(String args[])
{
try
{
//Connection with Server
Socket server=new Socket(“localhost”,1794);
Scanner sc=new Scanner(System.in);
//Object of Scanner to read from Server(Receive Data)
Scanner in=new Scanner(server.getInputStream());
//Object of PrintWriter to write on to the Server(Send Data)
PrintWriter out=new PrintWriter(server.getOutputStream(),true);//true means autoflush enabled no need to flush everytime(While Sending Data)
String s=””;
System.out.println(“Connected with Server”+”\n”);
do
{
System.out.print(“Client:”);
//accept input from user
s=sc.nextLine();
//send data
out.println(s);
//Receive Data
s=in.nextLine();
System.out.println(“Server:”+s);
}while(!s.equalsIgnoreCase(“bye”));
server.close();//close the socket
}
catch(Exception e)
{
}
}
}
/*Server Output
Client Connected
Client:hello
Server:hie
Client:name?
Server:darshan
Client:bye
Server:bye
*/
/*Client Output
Connected with Server
Client:hello
Server:hie
Client:name?
Server:darshan
Client:bye
Server:bye
*/
Thanks a lot for this detail about socket programming in java. As beginner i was looking for this socket programming guide and information. You have defined it so well as it is so important for making program run. Keep sharing.
I’m glad you found it useful, Priya.