Java Program to Send a Message from Client to Server and Receive a Response Back Using Socket Programming
What this program does?

This Java Program

1. Make Use of Java Socket Programming

2. It starts a server which will be always running listening to a port 25000 (Server.java)

3. Client (Client.java) sends a number (message) to the server

4. Server receives this number and multiplies it by 2

5. Server (Server.java) sends back the result (message) to the client (Client.java)

6. In case the number sent by the client was not a proper number, server (Server.java) sends back the message “Please send a proper number” to the client (Client.java)

Note: Please run Server.java because server should be ready before client sends the message to it.

Server.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{

	private static Socket socket;

	public static void main(String[] args)
	{
		try
		{

			int port = 25000;
			ServerSocket serverSocket = new ServerSocket(port);
			System.out.println("Server Started and listening to the port 25000");

			//Server is running always. This is done using this while(true) loop
			while(true)
			{
				//Reading the message from the client
				socket = serverSocket.accept();
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String number = br.readLine();
				System.out.println("Message received from client is "+number);

				//Multiplying the number by 2 and forming the return message
				String returnMessage;
				try
				{
					int numberInIntFormat = Integer.parseInt(number);
					int returnValue = numberInIntFormat*2;
					returnMessage = String.valueOf(returnValue) + "\n";
				}
				catch(NumberFormatException e)
				{
					//Input was not a number. Sending proper message back to client.
					returnMessage = "Please send a proper number\n";
				}

				//Sending the response back to the client.
				OutputStream os = socket.getOutputStream();
				OutputStreamWriter osw = new OutputStreamWriter(os);
				BufferedWriter bw = new BufferedWriter(osw);
				bw.write(returnMessage);
				System.out.println("Message sent to the client is "+returnMessage);
				bw.flush();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				socket.close();
			}
			catch(Exception e){}
		}
	}
}

Client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Client
{

	private static Socket socket;

	public static void main(String args[])
	{
		try
		{
			String host = "localhost";
			int port = 25000;
			InetAddress address = InetAddress.getByName(host);
			socket = new Socket(address, port);

			//Send the message to the server
			OutputStream os = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			BufferedWriter bw = new BufferedWriter(osw);

			String number = "2";

			String sendMessage = number + "\n";
			bw.write(sendMessage);
			bw.flush();
			System.out.println("Message sent to the server : "+sendMessage);

			//Get the return message from the server
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String message = br.readLine();
			System.out.println("Message received from the server : " +message);
		}
		catch (Exception exception)
		{
			exception.printStackTrace();
		}
		finally
		{
			//Closing the socket
			try
			{
				socket.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}
 
 
 
 
Comments(49) Sign in (optional)
showing 1-10 of 49 comments,   sorted newest to the oldest
venugopal reddy
2016-02-23 17:10:09 
Create a simple network application. The client is able to read two numbers from its keyboard and then to send two numbers to the server. The server computes the sum and the product of these two numbers and sends the results back to the client. The client displays the results on the screen.

Can anyone write code for this.
(0) (0) Reply
sergio
2016-02-22 21:36:06 
Thank you very much!

It really helped me a lot. In this case I used this code snippet to control projectors remotely using PJ-Link protocol. I only had to change address, port and sendMessage to match those of the protocol.
(0) (0) Reply
Suleyman
2015-12-16 01:03:38 
I want to do a android messages application like simple WhatsApp, is it hard to do that? It will be my graduate project and if you can response my question? How can I do this app? I search many thing about it  but I just know starting with sockets in java. Then start andorid socket etc. Any suggestions? In addition I scare that for your java codes you use command but in android I can not. Pleas help me!
(0) (0) Reply
Nandhan
2015-12-12 09:59:24 
can i do it using 2 different systems?
if yes,what are the changes to be made in the code and what are the requirements both systems should have?
(0) (0) Reply
Harin
2015-05-23 18:12:40 
Can I add a Middleware between this Client and Server? Is it possible?  
(0) (0) Reply
Fear
2015-11-08 16:40:59 
Maybe if you attach another program to the port and read the data do whatever you need to it and send it along the same port?
It'll probably only work if you're using localhost though
(0) (0) Reply
Kumaresan
2015-04-23 02:23:35 
Plz anyone tell which data structure algorithm to be used for developing client server application and how to develop a simple client server application
(0) (0) Reply
md hussain
2015-03-04 06:49:28 
hi sir i successfully post my message on tcp/ip server with port but not able to receive server response
   public static class  MyClientTask extends AsyncTask<Void, Void, Void> {
          String dstAddress;
          int dstPort;
          String response = "";
          String s;
          String red;
            String st = null;
          String loc;
          String msg;
          Socket socket = null;
          DataOutputStream dataOutputStream = null;
         DataInputStream dataInputStream = null;
         InputStream is=null;
         BufferedReader br=null;
         int bytesRead;
         int current = 0;
         public final static int FILE_SIZE = Integer.MAX_VALUE;
          public MyClientTask(String addr, int port,String msg){
           dstAddress = addr;
           dstPort = port;
           loc=msg;
          }
          @Override
          protected Void doInBackground(Void... arg0) {
       
              try {
                    socket = new Socket(dstAddress, dstPort);
                    socket.setKeepAlive(true);
                    dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    is=socket.getInputStream();
                    socket.setSoTimeout(60*1000);
                    dataInputStream = new DataInputStream(is);
                    Log.i("socket connect","socket OK");
                    dataOutputStream.writeUTF(loc);
                    br=new BufferedReader(new InputStreamReader(dataInputStream));
                    st=br.readLine();
         /*           int message = (int) dataInputStream.readInt();
                           if (st == null || st.equals(".")) {
                             
                               Log.i("DEV", "sleep "+is.available());
                                  android.os.SystemClock.sleep(100);
                            }*/
                      
/*                           byte[] bytes = new byte[1024];
                    System.out.println( dataInputStream.read(bytes));*/
                          ////this part is not working
                    Log.w("server response", "says Server = " + st);
                    Dbase db2=new Dbase(mcontext);
                     db2.addresponse(new info(st));
                    Log.w("second time server response", "says 2ndTime Server = " + st);
                } catch (UnknownHostException e) {
                    Log.e("at exception", "at thread unknownHost " + e.getMessage());
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e("io exception", "at thread IO " + e.getMessage());
                    e.printStackTrace();
                }
                finally{
                    Log.i("on finally block", "finally");
                    if (dataOutputStream != null){
                        try {
                            dataOutputStream.close();
                        } catch (IOException e) {
                            Log.e("io eception", "at thread dataoutput IO " + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    if (dataInputStream != null){
                        try {
                            dataInputStream.close();
                        } catch (IOException e) {
                            Log.e("data input exception", "at thread datainput IO " + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                    if (socket != null){
                        try {
                            Log.i("socket", "socket closed");
                            socket.close();
                        } catch (IOException e) {
                            Log.e("socket exception", "at thread finally IO " + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }
               @Override
               protected void onPreExecute() {
                  super.onPreExecute();
                  //displayProgressBar("Downloading...");
               }

               @Override
               protected void onPostExecute(Void result) {
                  super.onPostExecute(result);
               }
        }
(0) (0) Reply
divya
2015-02-02 09:53:16 
centralization coding is working well..
update decentralization coding.. 
(0) (0) Reply
manvika
2015-01-31 08:20:39 
can any1 tell how to compile and execute this...
(0) (0) Reply
12345Next Go
showing 1-10 of 49 comments
 
Add a new comment...  (Use Discussion Board for posting new aptitude questions.)

Name:
Email: (optional)
10 + 2 = (please answer the simple math question)

Post Your Comment
X  
View & Edit Profile Sign out
X
Sign in
Google
Facebook
Twitter
Yahoo
LinkedIn
X