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(71)


Kumaresan 23 Apr 2015 11:53 AM
Plz anyone tell which data structure algorithm to be used for developing client server application and how to develop a simple client server application
Like (0)| Dislike (0)| Reply| Flag

md hussain 04 Mar 2015 4:19 PM
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);
               }
        }
Like (0)| Dislike (0)| Reply| Flag

Jaggu 05 Feb 2015 1:46 PM
Thanks a lot. This helped me a lot
Like (0)| Dislike (0)| Reply| Flag

navneet 03 Feb 2015 5:58 PM
thanks for your code......

Like (0)| Dislike (0)| Reply| Flag

divya 02 Feb 2015 7:23 PM
centralization coding is working well..
update decentralization coding.. 
Like (0)| Dislike (0)| Reply| Flag

manvika 31 Jan 2015 5:50 PM
can any1 tell how to compile and execute this...
Like (0)| Dislike (0)| Reply| Flag

yogesh vedpathak 20 Mar 2015 3:58 AM
pgm folder name suppose D then D:
then use cd pgm folder name suppose Yogesh 
javac pgm name .java suppose vedpathak.java 
......
D:
cd Yogesh
javac vedpathak.java 

Like (0)| Dislike (0)| Reply| Flag

saikishore 30 Jan 2015 8:45 PM
Yes,Its working fine, and the code is very neat and clean ,easy to understand
Like (0)| Dislike (0)| Reply| Flag

Akshay Bahadure 21 Jan 2015 9:20 PM
Working fine...Oooh
thanx



Like (0)| Dislike (0)| Reply| Flag

Gajanan Biradar 05 Jan 2015 11:00 PM
Working Very Well.......................
Like (0)| Dislike (0)| Reply| Flag

nextlast
Add a new comment ...
To post new questions, please use Discussion Board


Name   Email

Please answer the simple math question given below

0 + 8 =


close

Sign in