2013-12-22 3 views
0

내 수석 프로젝트에 문제가 있습니다. 내 목표는 읽고 난에 대한 몇 가지 문제가 packet.But http 응답을 수정한다 java.net.SocketException Responsethread에서 예외 제발 도와"java.net.SocketException : 동료에 의한 연결 재설정 : 소켓 쓰기 오류"어떻게 해결할 수 있습니까?

여기
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) 


내 코드입니다
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(); 
    } 
} 
} 

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(); 
    } 
} 
} 


ResponseThread.java 저를 도와 주셔서 감사합니다 : D

+3

아니요, 여기에 모든 코드를 덤핑 해 주셔서 감사합니다. –

+0

while (bytesRead = is.read (buf))! = -1) ... 어떻게 초기화합니까 (InputStream 인스턴스)? 귀하의 코드를 명확히하십시오. – elbuild

+0

여기서는 int i = 0입니다. 사용 중 – Ashish

답변

0

이 예외는 일반적으로 이미 피어에 의해 손실 된었던 연결에 쓴 것을 의미한다. 즉, 응용 프로그램 프로토콜 오류입니다. 다른 원인이 있지만 이것이 가장 일반적입니다.

관련 문제