How to Fix Java.Net.Socketexception: Broken Pipe

Why a java.net.SocketException: Broken pipe will occur?

Some port scanners work by starting to open a connection and then immediately terminating it. Your server is not programmed to deal with a connection failure because you did not code for that possibility. You will need to use a try/catch to trap that condition and recover. Also, you should probably be handing off the connection to a separate thread for processing, so your main program can continue to receive new connections (and sending them to threads to be handled).

How to fix Broken Pipe Socket Exception (Java)? Where is connection being closed?

After much searching among different problems, I found the answer here.

The problem was with the response headers not being formatted properly which led to the connection ending prematurely. Another empty line ("\r\n") must be sent after the header.

The following code now works (this.CRLF is equal to "\r\n"):

    public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}

// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream()); // Data output
this.printOut = new PrintWriter(sock.getOutputStream()); // Print output
} catch (Exception e){
System.out.println(e);
}

// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}

StringTokenizer st = new StringTokenizer(reqMes);

// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");

// Initialize file to be sent
File file = null;
// Try to find file and create input stream
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}

byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
this.out.writeBytes(this.CRLF);
this.out.flush();

// Read file data
byte[] fileData = new byte[1024];

int i;
while ((i = this.f.read(fileData)) > 0) {
// Write File data
try{
this.out.write(fileData,0, i);
} catch (IOException e) {
System.out.println(e);
}
}
this.out.flush(); // Flush output stream
System.out.println("Flushed");
closeSock(); // Closes socket
} catch (IOException e) {
e.printStackTrace();
}

Apache HttpClient 4.5.13 java.net.SocketException: Broken pipe (Write failed)

I was facing a similar issue, I fixed it including the following configuration to the httpClient

RequestConfig requestConfig = RequestConfig.custom()
.setExpectContinueEnabled(true).build();
HttpClientBuilder clientBuilder = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig);
CloseableHttpClient httpClient = clientBuilder.build();

And in the next link you can found the explanation to do it http://httpcomponents.10934.n7.nabble.com/Broken-pipe-Write-failed-when-making-Unauthorized-request-td34235.html.

Edit: The link above is broken so here is a similar link that works: https://lists.apache.org/thread/p38b3lrjt4vhyqthwhqcq3vsx3dpr3wj

Here is the summary that Joe asked for:
The scenario is that a server rejects a request based on headers and closes the connection so the client gets a broken pipe error. The expect-continued header tells the client to look for a 100 status indicating that the server has accepted the headers and the client should send the rest of the data. Note that not all servers appear to do this correctly and can still close the connection after sending the 100 status.



Related Topics



Leave a reply



Submit