Socket会在所有io流关闭后自动关闭。错误代码如下:
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Client is sending message".getBytes(StandardCharsets.UTF_8));
socket.shutdownOutput();
outputStream.close();
InputStream inputStream = socket.getInputStream();
byte[]buf=new byte[1024];
int readlen=0;
while((readlen=inputStream.read(buf))!=-1)
{
System.out.println(new String(buf,0,readlen));
}
inputStream.close();
System.out.println("客户端退出");
可以看到在inputstream创建之前outputstream已经关闭了,由于在服务器端代码如下:
int ok=0;
while((readlen=inputStream.read(buf))!=-1)
{
ok=1;
System.out.println(new String(buf,0,readlen));
}
OutputStream outputStream=null;
if(ok==1) {
outputStream = accept.getOutputStream();
outputStream.write("I know.".getBytes(StandardCharsets.UTF_8));
accept.shutdownOutput();
}
if(outputStream!=null) outputStream.close();
inputStream.close();
accept.close();
serverSocket.close();
System.out.println("server exit with ok");
运行结果输出了server exit with ok
可以看出服务器端是正常运行的,两端的输入输出流互不影响。客户端输入流输出数据,服务器端接受到数据,此时客户端关闭了输出流(错误)
关闭后客户端的socket自动关闭了,后面客户端又想用socket的getInputStream方法所以会报错。
解决方法就是把客户端的outPutStream.close()语句挪到下面,所有io流一起关闭。