Echo server is a simple server with only one job to send back whatever is sent to it.
This post is about creating a simple Echo server on your local machine using JAVA programming language.
Step 2 : take ip address and port number as inputs from the user.
Step 3 : bind the ip address and the port number to the echo server socket created in step 1.
Step 4 : wait for the client's request.
Step 5 : once the client is connected to the echo server, assign it an independent thread for further execution.
[Note : Each client will be assigned a different independent thread]
Step 6 : the work of each thread is to simply send back the information received from the client.
Programs are quite self explanatory as comments are added when and where necessary.
First is the Echo Server program that actually creates the echo server for the clients to connect.
Second is an optional program to connect to Echo Server.
If you are familiar with telnet or similar applications, you can connect to echo server using them and skip the Client program provided.
[Note : Program seems to be in plain text here, I am working on it. Till then copy it to your editor so that keywords are highlighted]
1. Echo Server Program
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;
public class EchoServer {
public static void main(String args[]){
try{
// echo server socket
ServerSocket serverSocket;
// total number of clients
int clientCount = 0;
// echo server socket address
SocketAddress serverSocketAddress;
// to obtain input from standard input i.e. keyboard
Scanner scanner = new Scanner(System.in);
// getting socket address from user to create echo server socket
System.out.println("Socket Address :- \n");
System.out.print("\tIP Address :\t");
String serverIP = scanner.next();
System.out.print("\tPort number :\t");
short serverPort = Short.parseShort(scanner.next());
serverSocketAddress = new InetSocketAddress(InetAddress.getByName(serverIP), serverPort);
// creation & binding of echo server socket
// echo server socket creation
serverSocket = new ServerSocket();
// echo server binding
serverSocket.bind(serverSocketAddress);
if (serverSocket.isBound()){
System.out.println("Echo Server successfully bound to : " + serverSocketAddress);
}
else{
System.out.println("Echo Server binding unsuccessful");
System.exit(0);
}
while (true){
// listening and then accepting client's request to connect
Socket clientSocket = serverSocket.accept();
if (clientSocket.isConnected()){
System.out.println("\nConnected to "+clientSocket.getInetAddress() + '\n');
clientCount++;
// client count as thread name
String threadName = Integer.toString(clientCount);
Clients client = new Clients(threadName, clientSocket);
}
}
}catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
}
class Clients implements Runnable{
// client thread
private Thread clientThread;
// client socket to communicate
private Socket clientSocket;
// constructor to initialize the constructor class
Clients(String clientId, Socket clientSocket){
// thread name as client id
clientThread = new Thread(this, clientId);
this.clientSocket = clientSocket;
// calls the run method
clientThread.start();
}
public void run(){
// Scanner object to read data from the standard input
Scanner scanner = new Scanner(System.in);
// TODO : for the time being only one msg
try{
while (true){
// to map the received bytes from client to characters
InputStreamReader inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
// to store charset mapped received data
char[] recvData = new char[100];
// reading data from the input stream
inputStreamReader.read(recvData, 0, recvData.length);
System.out.println("Client "+clientThread.getName()+ " : " + new String(recvData));
// sending data to the client
clientSocket.getOutputStream().write(new String(recvData).getBytes());
}
} catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
}
2. Client Program
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client{
public static void main(String args[]){
// object of Scanner class to handle standard input
Scanner scanner = new Scanner(System.in);
// server socket to communicate with the server
Socket serverSocket;
try{
// getting server socket address from the user to connect
System.out.println("Server Socket Address :- \n");
System.out.print("\tIP Address :\t");
String serverIP = scanner.next();
System.out.print("\tPort number :\t");
short serverPort = Short.parseShort(scanner.next());
// connecting to the specified server
serverSocket = new Socket(InetAddress.getByName(serverIP), serverPort);
if (serverSocket.isConnected()){
System.out.println("\nConnected to "+ serverSocket.getInetAddress() + "\n");
} else{
System.out.println("\nConnection FAILED ");
return;
}
while (true){
// data to send to the Echo Server
String dataToSend="";
// to store charset mapped received data
char[] recvData = new char[100];
// to map the received bytes from the echo server to characters
InputStreamReader reader = new InputStreamReader(serverSocket.getInputStream());
System.out.print("Me : ");
// nextLine() must read my input and not the pre existing \n in buffer
while(dataToSend.length()==0)
dataToSend = scanner.nextLine();
// sending data to the server
serverSocket.getOutputStream().write(dataToSend.getBytes());
// receiving data from the server
reader.read(recvData, 0, recvData.length);
System.out.println("Server : " + new String(recvData));
System.out.println();
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Once Echo Server is created, execute the client program
This post is about creating a simple Echo server on your local machine using JAVA programming language.
STEPS INVOLVED
Step 1 : create a socket for the echo server.
Step 2 : take ip address and port number as inputs from the user.
Step 3 : bind the ip address and the port number to the echo server socket created in step 1.
Step 4 : wait for the client's request.
Step 5 : once the client is connected to the echo server, assign it an independent thread for further execution.
[Note : Each client will be assigned a different independent thread]
Step 6 : the work of each thread is to simply send back the information received from the client.
PROGRAM :-
Programs are quite self explanatory as comments are added when and where necessary.
First is the Echo Server program that actually creates the echo server for the clients to connect.
Second is an optional program to connect to Echo Server.
If you are familiar with telnet or similar applications, you can connect to echo server using them and skip the Client program provided.
[Note : Program seems to be in plain text here, I am working on it. Till then copy it to your editor so that keywords are highlighted]
1. Echo Server Program
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;
public class EchoServer {
public static void main(String args[]){
try{
// echo server socket
ServerSocket serverSocket;
// total number of clients
int clientCount = 0;
// echo server socket address
SocketAddress serverSocketAddress;
// to obtain input from standard input i.e. keyboard
Scanner scanner = new Scanner(System.in);
// getting socket address from user to create echo server socket
System.out.println("Socket Address :- \n");
System.out.print("\tIP Address :\t");
String serverIP = scanner.next();
System.out.print("\tPort number :\t");
short serverPort = Short.parseShort(scanner.next());
serverSocketAddress = new InetSocketAddress(InetAddress.getByName(serverIP), serverPort);
// creation & binding of echo server socket
// echo server socket creation
serverSocket = new ServerSocket();
// echo server binding
serverSocket.bind(serverSocketAddress);
if (serverSocket.isBound()){
System.out.println("Echo Server successfully bound to : " + serverSocketAddress);
}
else{
System.out.println("Echo Server binding unsuccessful");
System.exit(0);
}
while (true){
// listening and then accepting client's request to connect
Socket clientSocket = serverSocket.accept();
if (clientSocket.isConnected()){
System.out.println("\nConnected to "+clientSocket.getInetAddress() + '\n');
clientCount++;
// client count as thread name
String threadName = Integer.toString(clientCount);
Clients client = new Clients(threadName, clientSocket);
}
}
}catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
}
class Clients implements Runnable{
// client thread
private Thread clientThread;
// client socket to communicate
private Socket clientSocket;
// constructor to initialize the constructor class
Clients(String clientId, Socket clientSocket){
// thread name as client id
clientThread = new Thread(this, clientId);
this.clientSocket = clientSocket;
// calls the run method
clientThread.start();
}
public void run(){
// Scanner object to read data from the standard input
Scanner scanner = new Scanner(System.in);
// TODO : for the time being only one msg
try{
while (true){
// to map the received bytes from client to characters
InputStreamReader inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
// to store charset mapped received data
char[] recvData = new char[100];
// reading data from the input stream
inputStreamReader.read(recvData, 0, recvData.length);
System.out.println("Client "+clientThread.getName()+ " : " + new String(recvData));
// sending data to the client
clientSocket.getOutputStream().write(new String(recvData).getBytes());
}
} catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
}
2. Client Program
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client{
public static void main(String args[]){
// object of Scanner class to handle standard input
Scanner scanner = new Scanner(System.in);
// server socket to communicate with the server
Socket serverSocket;
try{
// getting server socket address from the user to connect
System.out.println("Server Socket Address :- \n");
System.out.print("\tIP Address :\t");
String serverIP = scanner.next();
System.out.print("\tPort number :\t");
short serverPort = Short.parseShort(scanner.next());
// connecting to the specified server
serverSocket = new Socket(InetAddress.getByName(serverIP), serverPort);
if (serverSocket.isConnected()){
System.out.println("\nConnected to "+ serverSocket.getInetAddress() + "\n");
} else{
System.out.println("\nConnection FAILED ");
return;
}
while (true){
// data to send to the Echo Server
String dataToSend="";
// to store charset mapped received data
char[] recvData = new char[100];
// to map the received bytes from the echo server to characters
InputStreamReader reader = new InputStreamReader(serverSocket.getInputStream());
System.out.print("Me : ");
// nextLine() must read my input and not the pre existing \n in buffer
while(dataToSend.length()==0)
dataToSend = scanner.nextLine();
// sending data to the server
serverSocket.getOutputStream().write(dataToSend.getBytes());
// receiving data from the server
reader.read(recvData, 0, recvData.length);
System.out.println("Server : " + new String(recvData));
System.out.println();
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
HOW TO RUN THE PROGRAM?
First Echo Server program must be executed
- Compile and run the Echo Server Program.
- Enter the ip address assigned to your PC (type 127.0.0.1 if client program is also executed from the same machine).
- Enter any valid non-reserved port number.
- Echo Server is created. Now the program will wait for the clients to connect.
Once Echo Server is created, execute the client program
- Compile and run the Client Program.
- Enter the ip address and the port number of the echo server when prompted.
- Now you will be connected to the echo server.
- Whatever you send will be echoed back by the Echo Server.
No comments:
Post a Comment