java.net.SocketException: Broken pipe
java.net.SocketException: Broken pipe
生产上遇到一个问题,socket发生Broken pipe
错误,如下
这个问题跟踪了好几个月,始终没有模拟出为什么会发生Broken pipe。最后发现,是客户端设置了超时时间setSoTimeout
,也是神坑。
下面的例子可以完整的还原出Broken Pipe错误,请在linux底下运行。
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
Socket s = null;
try {
s = new Socket("127.0.0.1", 3113);
s.setSoTimeout(5000);
DataOutputStream out = new DataOutputStream(
s.getOutputStream());
//client->server
out.write("1111 from client".getBytes());
// server->client
DataInputStream in = new DataInputStream(s.getInputStream());
byte[] bytes = new byte[1024];
int len = in.read(bytes);
System.out.println("client:" + new String(bytes, 0, len));
out.write("2222 from client".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(3113);
Socket s = ss.accept();
//client->server
DataInputStream is = new DataInputStream(s.getInputStream());
byte[] buf =new byte[1024];
int len = is.read(buf);
System.out.println("recv:"+new String(buf,0,len));
Thread.sleep(10000);
//server->client
s.getOutputStream().write("1111 server".getBytes());
//client->server
DataInputStream in = new DataInputStream(s.getInputStream());
byte[] bytes = new byte[1024];
int length = in.read(bytes);
try {
System.out.println("recv2:"+new String(bytes,0,length));
} catch (Exception e) {
e.printStackTrace();
System.out.println("--------------");
DataOutputStream out = new DataOutputStream(s.getOutputStream());
try {
out.write("error write ".getBytes());
} catch (IOException e1) {
System.out.println("==============================");
e1.printStackTrace();
}
}
}catch (Exception e){
System.out.println(e.getStackTrace());
e.printStackTrace();
}
}
}