有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法通过socket连接到linux计算机

我有一台服务器,运行在装有centos 7的linux机器上。 在这台机器上,我运行了一个代码来管理客户端与服务器的连接。 这是我的代码:

public class ServerMain_mng {
final static int nPort = 3333;

public static void main(String[] args) throws IOException {
    new ServerMain_mng();
}

public ServerMain_mng(){
    try {
        ServerSocket sSocket = new ServerSocket(3333);
        System.out.println("Server started at: " + new Date());
        System.out.println("===============================================\n");

        while(true) {
            System.out.println("waiting for connection");
            //Wait for a client to connect
            Socket socket = sSocket.accept();
            socket.setSoTimeout(30000);
            //Create a new custom thread to handle the connection
            ClientThread cT = new ClientThread(socket, nPort);
            //Start the thread!
            new Thread(cT).start();  
        }
    } 
    catch(IOException ex) {ex.printStackTrace();}
}}

问题是,当客户机试图连接到服务器时,代码没有越过Socket socket = sSocket.accept();

我应该注意的是,我在笔记本电脑上运行相同的代码,作为客户端从本地主机连接,运行良好。 我检查了路由器中的端口转发,指定的端口已打开

有什么问题吗?有办法解决吗? 任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    sSocket。accept()是一个阻塞调用,它应该保持阻塞状态,直到某个客户端使用它正在侦听的同一端口连接到它

     public class Client {
             final static int nPort = 3333;
             public static void main(String[] args) throws IOException {
             Socket sock=new Socket(IP of Server, nPort)
             System.out.println("connected to: +sock.getRemoteSocketAddress())
          //send additional data needed for the server using the socket's outputputStream
                }
                }
    

    在服务器上

     ClientThread cT = new ClientThread(socket);
      //Start the thread!
      new Thread(cT).start();