【发布时间】:2019-03-08 18:41:51
【问题描述】:
http 服务器没有响应 websocket
我无法让我的 http 服务器响应 websocket 请求。如何正确收听这些事件?我的服务器正在运行 SPA,我想尝试使用 websockets 不断将更新的信息从文件发送到客户端。我已经用 SSE 成功地做到了这一点,但对 websockets 很好奇。
我的 server.js 有以下内容
const http = require('http');
const WebSocket = require('ws');
var server = http.createServer(function(request, response) {
request.on('error', (err) => {
console.error(err.stack);
});
});
server.listen(8001);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function message(msg) {
console.log(msg);
});
});
});
我的客户端.js
var wsClient = ()=>{
const ws = new WebSocket('ws:'+serverip+'/WSindexJSON'); // this server is set through XHR request
ws.onopen = function(e) {
console.log("Connection established");
};
ws.addEventListener('open', () => {
// Send a message to the WebSocket server
ws.send('Hello!');
});
console.log("ws open",ws)
ws.addEventListener('message', event => {
// The `event` object is a typical DOM event object, and the message data sent
// by the server is stored in the `data` property
console.log('Received:', event.data);
});
}
我可以看到在 chrome 开发人员网络工具中创建的客户端 websocket,但服务器上没有任何内容。 我需要在服务器端创建 websocket 吗?
我看到了另一个服务器监听升级事件的例子。我试过了,没有成功。
server.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
console.log('server upgrade event websocket', pathname)
if (pathname === '/WSindexJSON') {
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
我还尝试了另一个 websocket 模块 const WebSocketServer = require('websocket').server; 并遇到了同样的问题。
【问题讨论】:
-
您的服务器代码未正确关闭!。你错过了关闭
});forhttpServer- 在修复你的代码应该可以工作之后! -
感谢您看到我将在这里编辑我的示例。这不是我的完整代码,只是 http 服务器的摘要。我的服务器可以正常工作,我可以连接到它并使用 GET POST 等响应