我正在尝试使用express和websocket模块使websokects与node.js一起工作
有趣的是,如果我使用http模块创建服务器,他们按预期工作,我收到状态101
但是,如果我使用快速模块来创建服务器,它将引发错误:
WebSocket connection to 'ws://localhost:2345/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
这是代码
// using http module (works)
var WebSocketServer = require("websocket").server;
var http = require("http");
var app = http.createServer(function(request, response) {
response.writeHeader(200, {'Content-Type':'text/html'});
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<script>"+
"var ws = new WebSocket('ws://localhost:2345/');"+
"ws.onmessage = function(event) { "+
"var span = document.createElement('span');"+
"span.innerHTML = event.data;"+
"document.body.appendChild(span);"+
"}"+
"</script>"+
"</head>"+
"<body>"+
"<span>Messages: </span>"+
"</body>"+
"</html>"
);
});
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
console.log("Connection ACCEPTED\n");
connection.on("message", function(message)
{
if(message.type == 'utf8')
{
console.log("Received Message: %s", message.utf8Data);
connection.sendUTF(message.utf8Data);
}
})
connection.on("close", function(reasonCode, description)
{
console.log("Connection lost\n");
})
})
和非工作部分
// using express module (get error)
var WebSocketServer = require("websocket").server;
var app = require('express')();
var app.get('/', function(request, response) {
response.writeHeader(200, {'Content-Type':'text/html'});
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<script>"+
"var ws = new WebSocket('ws://localhost:2345/');"+
"ws.onmessage = function(event) { "+
"var span = document.createElement('span');"+
"span.innerHTML = event.data;"+
"document.body.appendChild(span);"+
"}"+
"</script>"+
"</head>"+
"<body>"+
"<span>Messages: </span>"+
"</body>"+
"</html>"
);
});
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
console.log("Connection ACCEPTED\n");
connection.on("message", function(message)
{
if(message.type == 'utf8')
{
console.log("Received Message: %s", message.utf8Data);
connection.sendUTF(message.utf8Data);
}
})
connection.on("close", function(reasonCode, description)
{
console.log("Connection lost\n");
})
})
那里有什么问题?如何解决这个问题?
答案 0 :(得分:1)
Express中的app
不是httpServer
,因此,如果WebSocketServer
没有明确了解Express以及如何从中获取服务器,那么您可能需要通过更改它来为它提供实际的httpServer
对象而不是Express
对象:
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
到此:
var server = app.listen(2345);
var wsServer = new WebSocketServer({'httpServer': server});