Java 通过不同路由器的服务器套接字连接

Java Server Socket connection over different routers

我目前正在为一个小游戏开发客户端和服务器。 连接到服务器的客户端使用此方法建立连接:

// This method is called, passing on an ipv6 address and port number 6666
        public void startConnection(String ip, int port) throws IOException {
            try {
                clientSocket = new Socket(ip, port);
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                //some other code handling responses
            } catch (IOException e) {
                LOG.debug("Error when initializing connection", e);
                throw new IOException();
            }

        }

我构建的服务器接受使用此方法的连接:

 public void start(int port) {
        try {
            serverSocket = new ServerSocket(port); //port = 6666
//This part is used to handle multiple connections at once
        while (b){
            try {
                map.add(new EchoClientHandler(serverSocket.accept())); //EchoClientHandler is a class used to send and receive data instructions 
                x = map.size() - 1;
                System.out.println("Establishing connection from port " + port);
                map.get(x).start();
                System.out.println("Connection established");
            } catch (SocketTimeoutException e) {
                
            }
        }
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

这两种方法都可以正常工作并在客户端和服务器之间建立稳定的连接,但是当我尝试从不同的路由器或一般互联网连接(例如通过蜂窝数据)建立连接时它不起作用。 有没有一种方法可以在客户端和服务器不必从同一路由器连接的情况下建立连接?

编辑: 这是我从客户端得到的错误,服务器没有显示任何内容:

18:03:24.288 [AWT-EventQueue-0] DEBUG dorusblanken.werwolfclient.Client - Error when initializing connection

java.net.SocketException: Network is unreachable: connect

“网络不可达”表示无法从当前网络到达目标网络。

您提到您正在尝试通过 Internet 建立连接。为此,目标主机(您的服务器)必须连接到 Internet,它必须具有 public IP 地址,并且客户端在连接时需要使用 public IP 地址。

这是最简单的配置。大多数公司实际上并没有将他们的服务器直接放在 Internet 上。相反,public IP 通常属于 CDN 或 DDoS 缓解层,它将连接转发到负载均衡器,然后负载均衡器将连接转发到服务器。