简体   繁体   English

Java 套接字客户端端口转发

[英]Java socket client port forwarding

I'm currently coding a client-server java application.我目前正在编写客户端-服务器 java 应用程序。 I use the java socket api for sending data from the client to the server and vice-versa.我使用 java 套接字 api 将数据从客户端发送到服务器,反之亦然。 The server is running on windows on port 9001. The client is in a docker container on the same machine.服务器在端口 9001 上的 windows 上运行。客户端在同一台机器上的 docker 容器中。 What port do I have to bind in docker so that the client in the docker container can connect to the server?我需要在docker中绑定什么端口,才能让docker容器中的客户端连接到服务器?

I've tried binding the server port, which obviously didn't work because it's already taken by the server.我已经尝试绑定服务器端口,这显然不起作用,因为它已经被服务器占用了。

Connect to the server's IP:9001.连接到服务器的 IP:9001。 What won't work is if you try to connect to localhost, as from inside the docker container it would look like connecting to the same container.如果您尝试连接到本地主机,那是行不通的,因为从 docker 容器内部,它看起来像是连接到同一个容器。

Of course your server process needs to listen to IP:9001, and listening to localhost:9001 is not sufficient.当然你的服务器进程需要监听IP:9001,监听localhost:9001是不够的。

Regarding binding: The server opens a port for listening, and that is called binding.关于绑定:服务端开一个端口监听,称为绑定。 The client opens a port for sending (but this sending port address is taken from the ephemeral port range and thus irrelevant) and uses that port to connect to the server port.客户端打开一个发送端口(但这个发送端口地址是从临时端口范围中获取的,因此无关紧要)并使用该端口连接到服务器端口。

See also:也可以看看:

The client needs to connect to the host on port 9001.客户端需要通过端口 9001 连接到主机。

The common way to do that is to add the host-gateway as an extra host by adding --add-host=host.docker.internal:host-gateway as a parameter to your docker run command.常见的方法是通过将--add-host=host.docker.internal:host-gateway作为参数添加到docker run命令中,将host-gateway添加为额外的主机。

Then the client can connect to your server program using host.docker.internal as the hostname (and 9001 as the port name).然后客户端可以使用host.docker.internal作为主机名(和 9001 作为端口名)连接到您的服务器程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM