In our example we have a Server.java which as the name suggest acts as a server and we have a Client.java which will act as a client. In both we used a threading concept, for receiving and sending a message to and fro.
We used Socket programming concept of ServerSocket and Socket
Kindly go through the code and see output.
//Server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String args[]) throws IOException
{
//Register service on port 1436
ServerSocket serverSocket = new ServerSocket(1463);
//For taking input
final Scanner scan = new Scanner(System.in);
while(true)
{
//Wait and accept a connection of multiple client
final Socket socket=serverSocket.accept();
//Start new Thread for receiving message
new Thread(new Runnable()
{
public void run()
{ try
{
while(true)
{
DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.println(dis.readUTF());
}
}
catch (Exception ie)
{ }
}
}).start();
//Start new Thread for sending message
new Thread(new Runnable()
{
public void run()
{ try
{
while(true)
{
String userInput = scan.nextLine();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("Server says : "+userInput);
}
}
catch (Exception ie)
{ }
}
}).start();
}//while loop
}//main
}
//Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
public static void main(String args[]) throws IOException
{
//Open your connection to a server, at port 1436
final Socket socket = new Socket("localhost",1463);
//For taking input
final Scanner scan = new Scanner(System.in);
//Start new Thread for sending message
new Thread(new Runnable()
{
public void run()
{ try
{
while(true)
{
String userInput = scan.nextLine();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("Client says : "+userInput);
}
}
catch (Exception ie)
{ }
}
}).start();
//Start new Thread for receiving message
new Thread(new Runnable()
{
public void run()
{ try
{
while(true)
{
DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.println(dis.readUTF());
}
}
catch (Exception ie)
{ }
}
}).start();
}//main
}
Output
Please write your comments.