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


saroja 25 Jul 2014 5:51 AM
can we execute this by using only while loop,except try catch?
Like (0)| Dislike (0)| Reply| Flag

Brock 23 Jul 2014 11:09 AM
Thanks Working Fine For Me.....God Bless u :)
Like (0)| Dislike (0)| Reply| Flag

Chandan Singh 20 Jul 2014 2:52 PM
HI,
     I am not getting any response from server when  i am trying to give input from console.

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

prashant 07 Jul 2014 6:46 AM
thnax...........
Like (0)| Dislike (0)| Reply| Flag

rupesh 01 Jun 2014 2:06 PM
plz tell me how client listen continues  server response.......
Like (0)| Dislike (0)| Reply| Flag

mark hernandez 27 Apr 2014 3:46 PM
very nice script :) 

but idk it all not even java

im trying to find someone to make my mini idea


server irc.bot client
* sends msg to irc.bot (ip wan) holds msg *get msg (irc.bot)
- - *use msg (ip wan)
- - *connect to server (msg use)
*authenticate client - *refresh every X seconds
- - *check irc msg
- - *reloads
*if wan changes send msg to irc.bot ip wan - hold msg *refresh connection if found
- - ip is not = to previous ip



thx ^_^ cheers!

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

Ravish 07 Apr 2014 3:36 AM
Not working for me:

Message sent to the server : 2

Message received from the server : HTTP/1.1 400 Bad Request
Like (0)| Dislike (0)| Reply| Flag

Addisu 03 Apr 2014 4:05 PM
Pleace helep me!
Like (0)| Dislike (0)| Reply| Flag

ganesh 05 Apr 2014 2:16 PM
what is your doubt
Like (0)| Dislike (0)| Reply| Flag

Anisha Jain 20 Mar 2014 3:11 AM
i m getting an error
 java.net.SocketException:Network is down:Listen Failed
at java.net.PlainSocketImpl.socketListen<native method>
at java.net.PlainSocketImpl.listen<PlainSocketImpl.java:380>
at java.net.ServerSocket.bind<ServerSocket.java:320>
at java.net.ServerSocket.<init><ServerSocket.java:185>
at java.net.ServerSocket.<init><ServerSocket.java:97>
at Server.main<Server.java:21>

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

next last
Add a new comment ...


Name   Email

Please answer the simple math question given below

3 + 9 =


close

Sign in