无法通过socket连接到linux机器

时间:2016-09-27 09:35:17

标签: java linux sockets network-programming

我有一台运行在带有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 个答案:

答案 0 :(得分:0)

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();
相关问题