gpt4 book ai didi

java - 连接被对等方重置 : socket write error

转载 作者:行者123 更新时间:2023-11-30 04:54:37 25 4
gpt4 key购买 nike

运行此代码时,我在最后一个 while 循环中的 OutputStream.write 上遇到异常(它在代码中的其他位置工作正常) - 这是在主机中搜索时在 java 中植入代理服务器-响应内容长度并将结果转发到浏览器,它可以工作,但是当尝试处理“Transfer-Encoding:分块”策略时,相同的方法不起作用'并抛出此异常:

 java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at IncomingRequest.run(IncomingRequest.java:250)

is = hostSocket.getInputStream();
OutputStream os = client.getOutputStream();

System.out.println("Forwarding request from server");

byte[] currByte = new byte[1];
StringBuilder responseHeader = new StringBuilder();
int crlfCounter = 4;

// Separates the response header by looking for 2 consecutive \r\n

while (crlfCounter > 0){
is.read(currByte);
os.write(currByte);
System.out.print((char)currByte[0]);
responseHeader.append((char)currByte[0]);
if ((char)currByte[0] == '\r' || (char)currByte[0] == '\n'){
crlfCounter--;
}else{
crlfCounter = 4;
}
}

StringBuilder chuckSize = new StringBuilder();
int contentLength = 0;
int contentIndex = responseHeader.toString().indexOf("Content-Length: ");
int chunkedIndex = responseHeader.toString().indexOf("Transfer-Encoding: chunked");
if (contentIndex != -1) {
contentIndex += 16;
int conEnd = responseHeader.toString().indexOf('\n', contentIndex);
contentLength = Integer.parseInt(responseHeader.toString().substring(contentIndex,conEnd).trim());
System.out.println("Content Length is : " + contentLength);
while (contentLength > 0){
is.read(currByte);
os.write(currByte);
contentLength--;
}
os.write('\r');
os.write('\n');
os.write('\r');
os.write('\n');
} else if (chunkedIndex != -1){
boolean lastChunk = false;
while (!lastChunk) {

do {
is.read(currByte);
chuckSize.append((char) currByte[0]);
} while ((char)currByte[0] != '\n');

contentLength = Integer.parseInt(chuckSize.toString().trim(), 16);
System.out.println("Hex " + chuckSize.toString());
System.out.println(contentLength + " the number");

if (contentLength == 0) {
lastChunk = true;
}

while (contentLength > 0){
is.read(currByte);
os.write(currByte);
contentLength--;
}
}
}

最佳答案

我可能误读了您的代码,但似乎您将所有 header (包括“Transfer-Encoding:chunked”)写入了os,但您没有写入实际的 block 大小,所以接收端可能因为非法输入而关闭连接(期望 block 大小,获取其他数据)

关于java - 连接被对等方重置 : socket write error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8944826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com