gpt4 book ai didi

javascript - WinRT - StreamSocket - 通过 LoadAsync 读取数据时关闭连接

转载 作者:行者123 更新时间:2023-11-30 18:11:43 24 4
gpt4 key购买 nike

我正在尝试通过 StreamSocket 发送 HTTP 请求,但响应被 chop 为

“failedWinRTError:对象已关闭。”


这是我的代码:

  var count, hostName, raw_request, raw_response, reader, socketProtection, startReader, streamSocket, writer;
streamSocket = new Windows.Networking.Sockets.StreamSocket();

hostName = new Windows.Networking.HostName("www.reddit.com", "80");

raw_response = "";

count = 0;

startReader = function() {
return reader.loadAsync(8 * 1000).done(function(bytesRead) {

raw_response += reader.readString(reader.unconsumedBufferLength);
if (raw_response.indexOf("</html>") > 0) {
return;
} else {
startReader();
}
}, function(error) {

raw_response += reader.readString(reader.unconsumedBufferLength);
window.raw_response = raw_response;
return;
});
};

streamSocket.connectAsync(hostName, "80", 0).done(function(response) {
var string;

reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = 1;

writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
string = "Hello world";
writer.writeString(raw_request);
return writer.storeAsync().done(function() {
writer.flushAsync();
writer.detachStream();
return startReader();
});
});

我注意到响应的开头也被 chop 了。

这是我在 HTTP 响应开始时得到的。

/1.1 200 OK

同样奇怪的是......HTTPS 请求工作得很好。


知道我做错了什么吗?谢谢:)

最佳答案

去掉主机名中的http://,第二个参数就不需要了:

var hostName = new Windows.Networking.HostName("www.reddit.com");

ConnectAsync 中使用这个对象,只需要主机名和服务名参数:

streamSocket.connectAsync(hostName, "80").done(function (response) {
// ....
}, function (error) {
console.log(error);
});

更新: 好的,如果连接正在关闭,可能是服务器关闭了它。您发送的请求格式正确吗?这是一个例子:

var raw_request, raw_response, reader, writer;
var streamSocket = new Windows.Networking.Sockets.StreamSocket();

function doRequest() {
var hostName = new Windows.Networking.HostName("www.reddit.com");
streamSocket.connectAsync(hostName, "808").then(function () {
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = Windows.Storage.Streams.InputStreamOptions.partial;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);

raw_request = "GET / HTTP/1.1\r\nHost: www.reddit.com/\r\nConnection: close\r\n\r\n";
writer.writeString(raw_request);
return writer.storeAsync();
}).then(function () {
raw_response = "";
return startReader();
}, function (error) {
console.log(error);
});
}

function startReader() {
return reader.loadAsync(99999999).then(function (bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (bytesRead === 0) {
window.raw_response.value = raw_response;
return;
}
return startReader();
});
};

关于javascript - WinRT - StreamSocket - 通过 LoadAsync 读取数据时关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14426350/

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