简体   繁体   English

无法通过套接字连接到Linux计算机

[英]unable to connect to linux machine through socket

I have aa server running on a linux machine with centos 7. On the machine I run a code the manages client connections to the server. 我有一台运行在具有centos 7的Linux机器上的服务器。在这台机器上,我运行一个代码来管理与服务器的客户端连接。 Here is my code: 这是我的代码:

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();}
}}

The problem is that the code does not get past the line Socket socket = sSocket.accept(); 问题是代码无法通过Socket socket = sSocket.accept(); when a client tries to connect to the server. 当客户端尝试连接到服务器时。

I should note that i run the same code on my laptop, connecting as a client from a local host and it works fine. 我应该注意,我在笔记本电脑上运行相同的代码,从本地主机作为客户端连接,并且运行良好。 I checked the port forwarding in the router and the specified ports are open. 我检查了路由器中的端口转发,并打开了指定的端口。

What could be the problem? 可能是什么问题呢? Any ideas how to fix it? 任何想法如何解决? any help would be appreciated. 任何帮助,将不胜感激。

sSocket.accept() is a blocking call, it is supposed to remain blocked untill some client connects to it using the same port where it is listening. 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
            }
            }

At the server, 在服务器上,

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

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

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