1

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

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

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

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

/1.1 200 确定

同样奇怪的是...... HTTPS 请求完美运行。


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

4

1 回答 1

2

从主机名中删除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();
    });
};
于 2013-01-20T20:38:03.423 回答