我正在尝试实现一个简单的 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 MUST wait for a response from the server before sending any further data. The client MUST validate the server's response as follows:
- If the status code received from the server is not 101, the client handles the response per HTTP [RFC2616] procedures. In particular, the client might perform authentication if it receives a 401 status code; the server might redirect the client using a 3xx status code (but clients are not required to follow them), etc. Otherwise, proceed as follows.
第 4.2.2 节详细说明:除了使用代码 101 和适当的 header 进行响应之外,服务器可能会要求身份验证(响应代码 401),可能会重定向(3xx 代码),并且如果您尝试建立安全连接,则应该执行 TLS 握手(如果您使用 wss://
协议(protocol))。
位于 localhost:52312
的服务器响应代码 200 - websocket 标准,如您在上面看到的,在此响应中没有定义任何意义。因此,客户有权利提出异常(exception)。问题出在服务器上。
关于html - 与 'ws://localhost:52312/' 的 WebSocket 连接失败 : Error during WebSocket handshake: Unexpected response code: 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639812/