2012-05-16 155 views
0

当过我运行服务器后运行客户端,与错误的连接服务器崩溃复位......这里是我的代码:客户端/服务器应用程序连接重置的Java

启动客户端插座和连接到服务器。等待输入。 客户:

private Socket socket; 
private BufferedReader in; 
private PrintWriter out; 
private String fromServer,fromUser; 

public ClientTest() { 
    try { 
     socket = new Socket("127.0.0.1", 25565); 
     out = new PrintWriter(socket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
    } catch (UnknownHostException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public void start() { 
    try { 
     while ((fromServer = in.readLine()) != null) { 
      System.out.println(fromServer); 
      out.println("1"); 
     } 
     System.out.println("CLOSING"); 
     out.close(); 
     in.close(); 
     socket.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public static void main(String[] args) { 
    new ClientTest(); 
} 

启动服务器套接字和发送“2”客户端和启动对话

服务器:

public ServerTest() { 
    try { 
     serverSocket = new ServerSocket(25565); 
     clientSocket = serverSocket.accept(); 

    } 
    catch (IOException e) { 
     System.out.println("Could not listen on port: 4444"); 
     System.exit(-1); 
    } 
    start(); 
} 

public void start() { 

    try { 
     PrintWriter out; 
     out = new PrintWriter(clientSocket.getOutputStream(), true); 
     BufferedReader in; 
     in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     String inputLine, outputLine; 
     // initiate conversation with client 
     out.println("2"); 
      while ((inputLine = in.readLine()) != null) { 
       System.out.println(inputLine); 
       out.println("2"); 
      } 
     System.out.println("Stopping"); 
     out.close(); 
     in.close(); 
     clientSocket.close(); 
     serverSocket.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

public static void main(String[] args) { 
    new ServerTest(); 
} 

当过我运行服务器,一切都很好,但是当之后,我运行客户端服务器崩溃连接重置错误。

+0

你可以添加你的堆栈跟踪吗? – StepTNT

回答

1

ClientTest()不调用start()方法。您的客户在建立连接后立即退出。

+0

感谢它工作! – Trixmix

1

Alex的回答是对的。

该程序也进入无限循环。您需要在客户端和服务器的while循环中添加退出条件。

+0

但它立即崩溃说连接重置我不认为这与无限循环有什么关系 – Trixmix

+0

NVM它工作! – Trixmix

相关问题