今天在学习socket编程的时候遇到了一个bug:java.net.SocketException: Connection reset
先来看一下自己的代码:
服务端:
public class ServerSocketDemo {
public static void main(String[] args) {
try {
// 建立一个ServerSocket
ServerSocket serversocket = new ServerSocket(9999);
//等待连接
Socket socket = serversocket.accept();
//读取数据
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = bufferedReader.readLine();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
public class ClientSocketDemo {
public static void main(String[] args) {
try {
//建立Socket,指定服务端的ip地址和端口号
Socket socket = new Socket("127.0.0.1", 9999);
//往服务端发送数据
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String str = "你好,这是第一个socket程序";
bufferedWriter.write(str);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
先运行服务端,再紧接着运行客户端,客户端代码执行完毕后,然后查看服务端控制台,报错:java.net.SocketException: Connection reset。
错误的原因是,客户端代码没有进行关闭操作,加上这段代码就好了。
socket.shutdownOutput();
public class ClientSocketDemo {
public static void main(String[] args) {
try {
//建立Socket,指定服务端的ip地址和端口号
Socket socket = new Socket("127.0.0.1", 9999);
//往服务端发送数据
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String str = "你好,这是第一个socket程序";
bufferedWriter.write(str);
bufferedWriter.flush();
// 挂断电话,断开连接
// 一定要加上这段代码才行。关闭socket连接。
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:reset,SocketException,socket,String,bufferedWriter,new,net,服务端,Socket
From: https://www.cnblogs.com/dongyaotou/p/18191448