I'm trying to make websokects work with node.js using express and websocket modules.
The funny thing is that if I use the http module to create the server they work as expected, I receive status 101.
But if I use the express module to create the server it'll throw an error:
WebSocket connection to 'ws://localhost:2345/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
Here's the code
// 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");
})
})
and the non working part
// 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");
})
})
What could be wrong there? How to solve this issue?