Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some Problem with my senior project. my objective is read and modify http response packet.But I have some problem about java.net.SocketException help me please Exception at Responsethread

java.net.SocketException: Connection reset by peer: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:147)
    at helper.ResponseThread.run(ResponseThread.java:163)
BUILD STOPPED (total time: 4 minutes 3 seconds)


here is my code
Helper.java

package helper;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
 public class Helper {
  public void proc() {
    try {

        ServerSocket servsock = new ServerSocket(80);
        String hostname="www.hungeng.besaba.com";
        InetAddress ip=InetAddress.getByName(hostname);
        //int serverPort=3456;
        //Socket clientSocket =new Socket(ip,serverPort);
       //String ipAddr="31.170.164.70"; //http://hungeng.besaba.com/



        while (true) {

            Socket sockC = servsock.accept();

            //get input stream of the Socket(sockC) from Client 
            InputStream inC = sockC.getInputStream();
            //get output stream of the Socket(sockC) to Client
            OutputStream outC = sockC.getOutputStream();

            //Connect to the specified server(ipAddr) at the 80 port. 
            Socket sockS = new Socket(ip, 80);

            //get input stream of the Socket(sockS) from server(ipAddr)
            InputStream inS = sockS.getInputStream();
            //get output stream of the Socket(sockS) to server(ipAddr)
            OutputStream outS = sockS.getOutputStream();

            //Create Thread for sending The Request Message from Client 
            RequestThread request = new RequestThread();
            //Create Thread for sending The Response Message to Client
            ResponseThread response = new ResponseThread();

            // match a Request Thread with a Response Thread
            request.server = response;
            response.client = request;
            request.is = inC;
            request.os = outC;
            response.is = inS;
            response.os = outS;

            request.start();
            response.start();
        }
    } catch (Exception x) {
        x.printStackTrace();
    }

}
public static void main(String[] args) {
    // TODO code application logic here
     new Helper().proc();
}

}


RequestRhread.java

package helper;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class RequestThread extends Thread {
InputStream is;
OutputStream os;
ResponseThread server;
byte[] buf = new byte[1024];
int bytesRead;


public void run() {
    try {
       int i=0;


        while ((bytesRead = is.read(buf)) !=-1) {



            server.os.write(buf,0,bytesRead);


            server.os.flush();


        }

    } catch (Exception x) {
        x.printStackTrace();
    }
}
}


ResponseThread.java

package helper;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class ResponseThread extends Thread {
int num;
String content = "";
InputStream is;
OutputStream os;
RequestThread client;
byte[] buf = new byte[20000];
int bytesRead = 0;
String endMark = "\r\n\r\n";

public void run() {
    try {
        String msg = "";

        while ((bytesRead = is.read(buf)) != -1) {

            msg += new String(buf, 0, bytesRead);
          //  System.out.println("message");
            //System.out.println(msg);
           // System.out.println("---------");
            //client.os.write(buf, 0, bytesRead);
            int eHeader = msg.indexOf("\r\n\r\n");
            String header = msg.substring(0, eHeader + "\r\n\r\n".length());

            // System.out.println("header");
            //System.out.println(header);
            //System.out.println("-----------");
            int sConLength = header.indexOf("Content-Length: ");
            if (sConLength != -1) {
                //have content length  
                String temp = header.substring(sConLength);
                int eConLength = temp.indexOf("\r\n");
                int cl = Integer.parseInt(temp.substring("Content-Length: ".length(), eConLength));
                String uConlen = header.substring(0, sConLength + "Content-Length: ".length());
                System.out.println("uconlen ");
                System.out.println(uConlen);
                System.out.println("--------");

                String lConlen = temp.substring(eConLength + "\r\n".length());
                System.out.println("lconlen ");
                System.out.println(lConlen);
                System.out.println("-----------------");
                int sHtml = msg.toLowerCase().indexOf("<html>");
                int eHtml = msg.toLowerCase().indexOf("</html>");
                if ((sHtml != -1) && (eHtml != -1)) {
                    //has Html content
                    System.out.println(":::Have Html content:::");
                    int sForm = msg.toLowerCase().indexOf("<form");
                    int eForm = msg.toLowerCase().indexOf("</form>");
                    if ((sForm != -1) && (eForm != -1)) {
                        //have form
                        System.out.println(":::Have form:::");
                        String form = msg.substring(sForm, eForm + "</form>".length());
                        String uForm = msg.substring(eHeader + "\r\n\r\n".length(), sForm);
                        String lForm = msg.substring(eForm + "</form>".length());
                        String p = "<p id=\"demo\"></p>";
                        String bt = "<button type=\"button\" onclick=\"fill_in(name)\">Fill In</button>\n";
                        String[] data = {"Natta santawalim", "110033333333", "adressssss"};
                        String sc = "<script>\n ";
                        sc += "function fill_in(name) \n";
                        sc += "{\n";
                        sc += "document.getElementById(\"txtUsername\").value=\'";
                        sc += data[0];
                        sc += "\'; \n";
                        sc += "document.getElementById(\"txtPassword\").value=\'";
                        sc += data[1];
                        sc += "\'; \n";
                        sc += "document.getElementById(\"txtName\").value=\'";
                        sc += data[2];
                        sc += "\'; \n";
                        sc += "}\n";
                        sc += "</script>\n";

                        // client.os.write(result.getBytes());
                        cl += bt.length() + p.length() + sc.length();
                        client.os.write(uConlen.getBytes());
                        String l = Integer.toString(cl) + "\r\n";
                        client.os.write(l.getBytes());
                        client.os.write(lConlen.getBytes());
                        client.os.write(uForm.getBytes());
                        client.os.write(form.getBytes());
                        client.os.write(bt.getBytes());
                        client.os.write(sc.getBytes());
                        client.os.write(p.getBytes());
                        client.os.write(lForm.getBytes());

                        //                       System.out.println("byte "+);
                        //System.out.println("numofsent byr"+s);
                    } else {
                        //don't have form
                        System.out.println(":::Dont Have form:::");
                        //client.os.write(buf, 0, bytesRead);
                        String packet = msg.substring(eHeader + "\r\n\r\n".length());
                        client.os.write(header.getBytes());
                        client.os.write(packet.getBytes());

                        client.os.flush();
                    }

                } else {
                    // don't have Html content
                    System.out.println(":::Dont Have Html content:::");
                    client.os.write(buf, 0, bytesRead);
                    //client.os.flush();
                    //  num+=bytesRead;
                    //System.out.println("num "+num);
                }
            } else {
                //don't have content length,transfer-encoding: chunk
                System.out.println("chunk");
                //client.os.write(buf, 0, bytesRead);
                // System.out.println("message");
                //System.out.println(msg);
                int fChunk = header.indexOf("Transfer-Encoding: chunked");
            //    String m = msg.substring(eHeader + "\r\n\r\n".length());
                if (fChunk != -1) {
                    //chunk

                    int sHtml = msg.toLowerCase().indexOf("<html>");
                    int eHtml = msg.toLowerCase().indexOf("</html>");
                    if ((sHtml != -1) && (eHtml != -1)) {
                        //have html
                        String packet = msg.substring(eHeader + "\r\n\r\n".length());

                        String[] chunkPt = packet.split("\r\n");
                        //  System.out.println("=====chunk=========== ");

                        client.os.write(header.getBytes());
                        for (int i = 0; i < (chunkPt.length - 1); i++) {

                          int fForm=chunkPt[i].toLowerCase().indexOf("</form>");
                          if(fForm!=-1){
                               String bt = "<button type=\"button\" onclick=\"fill_in(name)\">Fill In</button>\n";
                               int btSizeDec=bt.length();
                               int cSizeDec=Integer.parseInt(chunkPt[i-1],16);
                               int totalSizeDec=btSizeDec+cSizeDec;
                               String totalSizeHex=Integer.toHexString(totalSizeDec);
                               String h=chunkPt[i].substring(0,fForm);
                               String t=chunkPt[i].substring(fForm);
                               chunkPt[i]=h+bt+t;
                               chunkPt[i-1]=totalSizeHex;
                               System.out.println("chunkEmbedded");
                               System.out.println(chunkPt[i]);


                          }
                            client.os.write((chunkPt[i]+"\r\n").getBytes());//Error occured here


                        }
                        client.os.write((chunkPt[chunkPt.length - 1] + "\r\n\r\n").getBytes());

                    } else {
                        System.out.println("dont hav html");
                        //dont have html
                    }

                } else {
                    //dont chunk
                    System.out.println("dont chunk");
                }
            }

        }
        client.os.flush();
    } catch (Exception x) {
        x.printStackTrace();
    }
}
}

Thank you for helping me :D

share|improve this question
3  
No, thank YOU for dumping all your code here instead of showing a token of effort by boiling it down to the essence. –  Marko Topolnik Dec 22 '13 at 16:45
    
while ((bytesRead = is.read(buf)) != -1) .... how do you initialize is (the InputStream instance)? Please clarify your code. –  elbuild Dec 22 '13 at 16:50
    
where is int i=0; being used –  Ashish Dec 22 '13 at 16:52
    
Can we have more code? –  Isaac Dec 22 '13 at 18:40

1 Answer 1

This exception usually means that you have written to an connection that had already been loses by the peer. In other words, an application protocol error. There are other causes, but this is the most common.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.