客户端关闭连接

时间:2011-11-28 01:51:40

标签: java sockets

我有一个套接字监听器,它一直在监听数据。现在的问题是发送数据的客户端最终将自己关闭连接。根据我的下面的代码,我想知道我还需要执行这部分代码吗writeBuffer.close();吗?

我应该删除最后一部分,只是让套接字关闭捕获?

public void run()
{   
     BufferedWriter writeBuffer = null;
     BufferedReader readBuffer = null;

     String message="";
     try {
         writeBuffer =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
         readBuffer = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));

         int m = 0, count=0;
         int nextChar=0;         

         while ((nextChar=readBuffer.read()) != -1) 
         {
          message += (char) nextChar;  
          if (nextChar == '#')
          {
              System.out.println("\n\nSending PA : "+message);
                  writeBuffer.write("$PA\r\n");
              writeBuffer.flush(); 
              message="";               
              }
         }
    } 
    catch (Exception ex)  
    { 
        System.out.println("MyError:Exception has been caught in in the main first try");
    ex.printStackTrace(System.out);
    }   
    /*finally
    {
        try 
        {
            if ( writeBuffer != null ) 
        {
            writeBuffer.close();
        }
            else 
        {
                System.out.println("MyError:writeBuffer is null in finally close");
        }
        }
        catch(IOException ex)
        {
            ex.printStackTrace(System.out);
        }
    }*/
}

1 个答案:

答案 0 :(得分:0)

明确关闭您正在使用的连接始终是个好主意。考虑一下,客户端可能永远不会关闭连接(当然,你必须实现某种超时机制,在一段时间后关闭服务器端的连接,但那个& #39;另一件事。)

我的观点是 - 小心谨慎,并以保守的方式管理你的资源。