我用Socket连接远端的一个端口进行通讯,当关闭后在连接就无法通讯了,报告Socket closed异常,这是为什么?有没有了解的,万分感谢!!!!以下是代码的例子:
Socket socket = null;
try {
socket = new Socket("10.128.0.202", 1024);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
os.write("AT\r".getBytes());
os.flush();
Thread.sleep(1000L);
int l = is.available();
byte[] b = new byte[l];
is.read(b);
System.out.println(new String(b));
// os.close();
// is.close();
socket.close();

socket = new Socket("10.128.0.202", 1024);
os = socket.getOutputStream();
os.write("AT\r".getBytes());
os.flush();
Thread.sleep(1000L);
l = is.available();
b = new byte[l];
is.read(b);
System.out.println(new String(b));
// os.close();
socket.close();
System.out.println("End");
} catch(UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(InterruptedException e) {
e.printStackTrace();
}
当调用第二个l = is.available();时就会报异常,那么应该如何完全关闭一个Socket?因为我需要在程序的不同地方分别连接,又不能让这个Socket一直连着。

解决方案 »

  1.   

    你的is被强制关闭了,所以会报nullpointexception
    你的os你都知道重新获取,为什么is就不重新获取呢?
    socket = new Socket("10.128.0.202", 1024); 
    os = socket.getOutputStream(); 
    os.write("AT\r".getBytes()); 
    os.flush(); 

    换成和最上面那里的一样
    socket = new Socket("10.128.0.202", 1024); 
    OutputStream os = socket.getOutputStream(); 
    InputStream is = socket.getInputStream();
    os.write("AT\r".getBytes()); 
    os.flush(); 
      

  2.   

    楼上正解!
    重新得到输入流!(InputStream)