我使用以下Java类建立了非常简单的套接字通信:
Server.java
:
public class Server
{
public static void main(String[] args) throws Exception
{
try (ServerSocket listener = new ServerSocket(59090))
{
while (true)
{
try (Socket socket = listener.accept())
{
Scanner in = new Scanner(socket.getInputStream());
while (in.hasNextLine())
{
System.out.println("UPPER CASE: " + in.nextLine().toUpperCase());
}
}
}
}
}
}
Client.java
:
public class Client
{
public static void main(String[] args) throws Exception
{
try (Socket socket = new Socket("172.17.0.2", 59090))
{
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (true)
{
Thread.sleep(1000);
out.println("hello world");
}
}
}
}
我想将它们作为单独的Docker容器运行,因此我创建了相应的Dockerfile
和docker-compose.yml
:
Dockerfile
(服务器):
FROM openjdk:13-ea-16-jdk-alpine3.9
RUN mkdir -p /app/server
WORKDIR /app/server
COPY ./Server.java ./
RUN javac Server.java
ENTRYPOINT ["java", "Server"]
Dockerfile
(客户端):
FROM openjdk:13-ea-16-jdk-alpine3.9
RUN mkdir -p /app/client
WORKDIR /app/client
COPY ./Client.java ./
RUN javac Client.java
ENTRYPOINT ["java", "Client"]
docker-compose.yml
:
version: "3.7"
services:
client:
image: utku/socket-client:0.1.0
build: ./client
server:
image: utku/socket-server:0.1.0
build: ./server
在使用docker-compose build
构建映像并首先运行server
然后使用client
运行docker run ...
之后,我看到服务器的IP变为172.17.0.2
,而客户端的IP成为172.17.0.3
。这就是为什么我在Client.java
的相应行中指定IP地址的原因:
// Client.java
try (Socket socket = new Socket("172.17.0.2", 59090))
Docker文档指出,我应该能够从server
访问client
,使用其服务名称为以下内容,即server
中的docker-compose.yml
。
// Client.java
try (Socket socket = new Socket("server", 59090))
但是,当我尝试用服务器的服务名称替换此IP地址时,出现以下错误:
Exception in thread "main" java.net.UnknownHostException: server
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:350)
at java.base/java.net.Socket.connect(Socket.java:620)
at java.base/java.net.Socket.connect(Socket.java:568)
at java.base/java.net.Socket.<init>(Socket.java:459)
at java.base/java.net.Socket.<init>(Socket.java:236)
at Client.main(Client.java:12)
您能指出我在这里缺少什么吗?
答案 0 :(得分:0)
您需要expose网络端口。您的docker-compose
文件应如下所示:
version: "3.7"
services:
client:
image: utku/socket-client:0.1.0
build: ./client
expose:
- "59090"
server:
image: utku/socket-server:0.1.0
build: ./server
expose:
- "59090"