Running a simple client server program in docker

Hey… I am just a beginner to Docker and was exploring the various features. I want to run a simple client server program in docker within java.
So I just used a Client.java and Server.java and then using those I built the docker images.
The code within java files are as below:
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 msg = "Hello from Client";
 
        String sendMessage = msg + "\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();
        }
    }
}
}

The code for Server.java is:
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);
                String returnMessage = "Hello from Server";
                String sendreturnMessage = returnMessage + "\n";
		//Sending the response back to the client.

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

Then as the next step I built the image files for both of these using the Dockerfile as
Dockerfile for building serverimage

FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]

Dockerfile for building clientimage
FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT [“java”]
CMD [“Client”]

Then I built is using
docker build -t serverimage:v1 .

and
docker build -t clientimage:v1 .

Then I tried to run these docker images however the serverimage started, but the client image threw an exception and failed to start up
docker run -d --name server serverimage:v1
docker run --name client clientimage:v1

I also tried to run the clientimage as:
docker run --name client --link server:jcs clientimage:v1

Could someone help me out to resolve this issue? I just want to try out the communication between two containers in the same docker for now?

Thanks

1 Like

Looks like you’re pretty close, just need to revise a bit to fit Docker’s networking model.

I’d suggest creating a user-defined network and using that to connect them. You can access containers in the same network via DNS entries (one for each container name).

Here’s an example to explain. In your case you will configure the client container to connect to the server DNS entry server (similar to how myserver is used below).

$ docker network create javaapp
451905b63038719be32c3029dd229d02260fdc6f5fcca136c063556d3f3714d4

$ docker run -d --net javaapp --name myserver nginx
4b8c235789b2b262190f39d1ca2495304ca4ffc84321a127ac1bb9a0b748c717

$ docker run --net javaapp nathanleclaire/curl curl myserver:80
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:05 --:--:--     0<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
100   612  100   612    0     0    120      0  0:00:05  0:00:05 --:--:--   99k
1 Like

Thanks very much for the note… that worked well for me… :slight_smile:

hey there. actually I am also getting the same problem… so can you show me the changes you made to run the application…

Hello … I am also trying a simple server-client application through Docker. Initially I was also getting the exception of “java.net.ConnectException: Connection refused (Connection refused)” from the client side but my server was running perfectly. I followed the above solution but it is not working for me. So I created first the user-defined network as mentioned above and then tried to catch the server container IP address through a shell script (using docker inspect command) and passed that to my client program. With this my client is perfectly connected to the server but after receiving one message my client is stopping and I am getting exception at the server side such as,

java.net.SocketException: Connection reset

The application is running fine in my Ubuntu 16:04 system but when I am using docker to run it I am getting the connection reset exception.

Here is my server program,

package testServerPackage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class serverSocket {

public static void main(String args[])
{
	
	
	Socket cSocket = null;
	ServerSocket ss = null;
	PrintWriter out = null; 
	BufferedReader in = null; 
	try {
		 ss = new ServerSocket(55101);
		 

			BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Server is bind to : " + ss.getLocalPort());
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	while(true)
	{
		System.out.println("waiting for client request ...");
		try {
			cSocket = ss.accept();
			
			out = new PrintWriter(cSocket.getOutputStream(),true);
			in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
			String input;
			while((input = in.readLine())!=null)
			{
				out.println(input);
				System.out.println("The input from client is: "+input);
			}
			System.out.println("Client is no more interested to send data");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

}

Docker file for server is,
FROM openjdk:8
MAINTAINER XYZ
COPY ./*.jar testDirServer/
EXPOSE 55101
WORKDIR testDirServer
CMD [“java”, “-jar” , “simpleTestServerClient.jar” , “2”]

Network creation : docker network create javaapp
Image building : sudo docker build -f Dockerfile --no-cache=true -t serverimage .
Running : sudo docker rm -f /serverRun;sudo docker run --network=javaapp --name serverRun serverimage

My client code is as follows,

package testClientPackage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class clientSocket {

public static void main(String args[])
{
	String hostAddress = "";
	System.out.println("Hello from client");
	BufferedReader br;
	try {
		br = new BufferedReader(new FileReader(args[1]));
		hostAddress = br.readLine();
	} catch (FileNotFoundException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
           System.out.println("outside of try block " + hostAddress);

		
		Socket ss;
		try {
			ss = new Socket(hostAddress,55101);
			//ss = new Socket("172.18.0.2",55101);
			
			PrintWriter out = new PrintWriter(ss.getOutputStream(),true);
			BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream()));

			BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
			
			String userInput ;
			out.println("Hi Server");
			
			while((userInput = stdIn.readLine()) != null)
			{
                                   //client not at all using this loop
				out.println(userInput);
				System.out.println("client trying to send input: " +userInput);
				System.out.println("server returns the output as :" + in.readLine());
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

}

}

At client side I am executing,
sh hostIP.sh ; sudo docker build -f Dockerfile --no-cache=true -t client .
sudo docker rm -f client;sudo docker run --network=javaapp --name client client

hostIP.sh contain the following code,
#!/bin/sh
rm -rf ipText
echo "Hello"
sudo docker inspect -f ‘{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}’ serverRun > ipText
chmod a+w ipText

Content of client docker file is,
FROM openjdk:8
MAINTAINER XYZ
COPY ./*.jar testDirClient/
ADD ipText .
EXPOSE 55101
WORKDIR testDirClient
CMD [“java”, “-jar” , “simpleTestServerClient.jar” , “1”, “/ipText”]

It would be great if you please tell what I am missing.

Have a try of this link: