In this tutorial, let’s run a Java socket client & a server in two separate Docker containers. Both the client & server are continuously run, and networked by creating a Docker network. MyClient.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.myapp; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class MyClient { public static void main(String[] args) throws IOException { if (args.length != 1) { System.err .println("Pass the server IP as the sole command line argument"); return; } try (Socket socket = new Socket(args[0], 8888); Scanner sc = new Scanner(System.in); Scanner in = new Scanner(socket.getInputStream())) { OutputStream os = socket.getOutputStream(); PrintWriter out = new PrintWriter(os); while (true) { while(sc.hasNextLine()) { String msg = sc.nextLine(); System.out.println("Client sending: " + msg); out.println(msg); out.flush(); System.out.println("Server response: " + in.nextLine()); } } } } } |
MyServer.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.myapp; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class MyServer { public static void main(String[] args) throws IOException { try (ServerSocket listener = new ServerSocket(8888)) { System.out.println("The server is running..."); while (true) { try (Socket socket = listener.accept(); Scanner in = new Scanner(socket.getInputStream())) { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); while (in.hasNextLine()) { String msg = in.nextLine(); System.out.println("Server received: " + msg); out.println(msg.toUpperCase()); } } } } } } |
Dockerfile.client
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
FROM alpine:3.6 MAINTAINER java-success.com WORKDIR /app USER root # install required packages RUN apk add --no-cache openssh openssl openjdk8 rsync bash procps nss maven # set JAVA_HOME ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk ENV PATH $PATH:$JAVA_HOME/bin COPY src/main/java/com/myapp/MyClient.java com/myapp/MyClient.java RUN javac com/myapp/MyClient.java EXPOSE 8888 ENTRYPOINT ["java"] CMD ["com.myapp.MyClient", "myserver"] |
Note that…