gpt4 book ai didi

html - WebSocket 连接到 'ws://localhost:52312/' 失败 : Error during WebSocket handshake: Unexpected response code: 200

转载 作者:行者123 更新时间:2023-12-03 11:51:42 24 4
gpt4 key购买 nike

我正在尝试实现一个简单的 HTML5 WebSocket,但是根本没有建立连接,并且在创建 WebSocket 对象时出现以下错误

WebSocket connection to 'ws://localhost:52312/' failed: Error during WebSocket handshake: Unexpected response code: 200



下面是代码
 document.addEventListener("DOMContentLoaded", function (event) {
function runHub() {
if ("WebSocket" in window) {

console.log('WebSocket is supported by your browser.');

//var serviceUrl = 'ws://localhost:52312/';
var serviceUrl = 'ws://localhost:52312/home/GetNotificationCount';

var protocol = 'Chat-1.0';
var socket = new WebSocket(serviceUrl);

socket.onopen = function () {
console.log('Connection Established!');
};

socket.onclose = function (error) {
console.log('Connection Closed!');
console.log('Error Occured: ' + JSON.stringify(error));
};

socket.onerror = function (error) {
console.log('Error Occured: ' + JSON.stringify(error));
};

socket.onmessage = function (e) {
if (typeof e.data === "string") {
console.log('String message received: ' + e.data);
}
else if (e.data instanceof ArrayBuffer) {
console.log('ArrayBuffer received: ' + e.data);
}
else if (e.data instanceof Blob) {
console.log('Blob received: ' + e.data);
}
};


if (!socket.readyState === WebSocket.CLOSED) {
socket.send($('#notificationCount').text);
//socket.close();

}

}
}

var run = setInterval(function () {
runHub();
}, 10000)
});

有人对此有任何想法吗?

最佳答案

根据https://www.rfc-editor.org/rfc/rfc6455#section-4.1

Once the client's opening handshake has been sent, the client MUSTwait for a response from the server before sending any further data.The client MUST validate the server's response as follows:


  1. If the status code received from the server is not 101, theclient handles the response per HTTP [RFC2616] procedures. Inparticular, the client might perform authentication if itreceives a 401 status code; the server might redirect the clientusing a 3xx status code (but clients are not required to followthem), etc. Otherwise, proceed as follows.

第 4.2.2 节详细说明:除了使用代码 101 和适当的 header 进行响应外,服务器可能会要求身份验证(响应代码 401),可能会重定向(3xx 代码),如果您尝试建立安全连接,则应执行 TLS 握手(如果您使用 wss:// 协议(protocol))。
服务器位于 localhost:52312以代码 200 响应 - 如您在上面看到的,websocket 标准在此响应中没有定义任何意义。因此,客户有权提出异常(exception)。问题出在服务器上。

关于html - WebSocket 连接到 'ws://localhost:52312/' 失败 : Error during WebSocket handshake: Unexpected response code: 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639812/

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