正在关闭客户端内的读取器/输入/套接字



我目前正在编写一个多客户端聊天程序,它运行得非常好。我现在唯一的问题是它是否被强制关闭

我得到这个:

java.net.SocketException: Connection reset

我认为(从四周来看)这与没有正确关闭客户端内的流/套接字有关。。然而,我已经尝试了很多地方来关闭所有的东西,但我似乎无法解决。有人能给我指正确的方向吗?

这是客户端:(没有GUI的东西)套接字和流被定义为属性。

    public void connectToServer(){
      try{
         System.out.println("Waiting to connect");
         s = new Socket("localhost", 16789);   
         System.out.println("Connected");
         ClientThread ct = new ClientThread();
         ct.start(); 
         openStreams();         
      }
      catch(EOFException eofe){
         System.out.println("EOFException");
      }
      catch(IOException ioe){
         System.out.println("IO Error");
      }
   }
   public void openStreams(){
      try {
      //open input streams
         InputStream in = s.getInputStream();
         br = new BufferedReader(
                              new InputStreamReader(in));                             
      //open output streams
         OutputStream out = s.getOutputStream();
         pw = new PrintWriter(
                       new OutputStreamWriter(out));
      }
      catch(ConnectException ce){
         System.out.println("Could not connect");
      }
      catch(IOException ioe){
         System.out.println("IO Error");
      }
      catch(NullPointerException npe){
         System.out.print("Server offline");
         System.exit(0);
      }
   }
   public void closeStreams(){
      try{
         pw.close();
         br.close();
         s.close();
         }
      catch(IOException ioe){
         ioe.printStackTrace();
      }
   }
   public void sendMsg(){    
      String message = enterMsg.getText();
      pw.println(message);
      pw.flush();
   }
   public void showMsg(){
      String show;
      try{
         while((show = br.readLine()) != null){
            chatArea.append(show + " n");   
         }
      }
      catch(IOException ioe){
         chatArea.append("Error showing msg n");
      }   
   }   
   class ClientThread extends Thread {
      public void run(){
            showMsg();
            closeStreams();
      }   
   }
}

服务器指向的特定部分出现错误:

     while( ( msg = br.readLine()) != null ){  
        System.out.print(msg);            
        // convert & send msg to client
           for(PrintWriter pw : clients){
              pw.println(userName + ":" + msg );
              pw.flush();
           }     
        }
java.net.SocketException: Connection reset

最常见的原因是:

  1. 您写信给对等方已经关闭的连接
  2. 对等方在未读取所有挂起的传入数据的情况下关闭了连接

正确的恢复方法是关闭套接字并忘记该对等点,但两者都是应用程序协议错误,应该进行调查。

这与客户端中未正确关闭流/套接字有关

不,不是。这与过早地关闭它们有关,无论哪一个同行没有得到这个异常。

至于"正确关闭流",只需关闭PrintWriter.。关闭Socket的输入或输出流会关闭另一个流和套接字本身,您应该选择最外面的输出流/写入程序来关闭,这样它就会被刷新。

最新更新