2016-04-21 80 views
-1

我有一个void方法,称为startServerConnection(),将服务器连接到端口,在本例中为7777.此方法在另一个类的按钮ClientGUI的动作侦听器中调用。服务器未连接

我敢肯定的代码是正确的,但由于某种原因,我得到的唯一输出是"Waiting for connection..."

public void startServerConnection(){ 
     try{ 
      serverSocket = new ServerSocket(portNumber); 

      while(true){ 
       System.out.println("Waiting for a connection..."); 
       Socket clientSocket = serverSocket.accept(); 
       System.out.println("Connection established on port: "+clientSocket.getLocalPort()); 
       ClientConnection clientConnection = new ClientConnection(clientSocket); 
       Thread thread = new Thread(clientConnection); 
       thread.start(); 
      } 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      return; 
     } 
    } 

编辑 客户端类,connectClient方法:

public void connectClient(String user){ 
     try{ 
      host = clientSocket.getInetAddress(); 
      clientSocket = new Socket(host,port); 
      new ClientHandler(clientSocket).run(); 
      String accepted = "Connection for host "+host+" accepted on port: "+clientSocket.getPort(); 
     } 
     catch(Exception e){ 
      //sendMessage("Connection error: "+e); 
      //serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect"); 
     } 

    } 

任何有什么问题的想法?

+0

服务器无法连接。客户连接;服务器接受。如果你的服务器永远不会接受'accept()',客户端必须得到一个异常。它是什么?注意你不会通过评论可以告诉你的唯一代码来找出答案。并且不要破坏你自己的帖子。 – EJP

回答

1

更新:

public void connectClient(String user){ 
    try{ 
     clientSocket = new Socket(host,port); 
     // Use PrintWriter to send data out to server 
     // Use BufferedReader to receive data from server 
    } 
    catch(Exception e){ 
     //sendMessage("Connection error: "+e); 
     //serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect"); 
    } 
} 

主机的IP地址或主机名,如果服务器/客户端在同一台机器上运行,您可以使用“127.0.0.1”或“localhost”的;端口是int一个值,你的情况是7777

原文:

accept()是阻塞函数。之后的代码将不会彻底,直到连接建立。

你必须建立连接的客户端和请求,一旦服务器和客户端的连接,你会看到“端口上建立的连接。”

公共插座接受()抛出IOException异常

侦听与此套接字的连接并接受它。该方法会阻塞,直到建立连接。

+0

请检查编辑 – Guest

+0

是的,我也正在阅读你刚发给我的链接。写消息我会在另一个处理每个客户端实例的类中完成。我努力了解'host'。这应该是一个用户名或IP地址? – Guest

+0

我认为主机是IP地址,因此host.getInetAddress()并将其传递到套接字。 – Guest