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?
The app in Express is not the httpServer, so if the WebSocketServer doesn't explicitly know about Express and how to get the server from it, then you probably need to give it the actual httpServer object rather than the Express object which you can do by changing this:
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
to this:
var server = app.listen(2345);
var wsServer = new WebSocketServer({'httpServer': server});
Related
I am using nodejs to run the server, there is no log file
This is my server.js
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const wss = new ws.Server({noServer: true});
function accept(req, res) {
// all incoming requests must be websockets
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}
// can be Connection: keep-alive, Upgrade
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}
function onConnect(ws) {
ws.on('message', function (message) {
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
ws.send(`${name}!`);
//setTimeout(() => ws.close(1000, "Bye!"), 5000);
});
}
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
This is my code in react
componentDidMount() {
var connection = new WebSocket('wss://localhost:8000/');
connection.onopen = function(e) {
connection.send("add people");
};
connection.onmessage = function(event) {
// alert(`[message] Data received from server: ${event.data}`);
console.log("output ", event.data);
};
}
While I am trying to connect with web-socket with my jsx file its give me an error which is Firefox can’t establish a connection to the server at wss://localhost:8000/.
Your implementaion needs some changes. In the backend server, you forgot to call the onConnect function. So your ws.on method will never call.
Also, you imported the ws and create a WebSocket server wss, but you add some event listener on ws wrongly, you should add listener on your Websocket instance (wss):
// rest of the codes ...
const was = new ws.Server({noServer: true})
wss.on('connection`) {
// do something here ...
}
// rest of the codes ...
https.createServer(options, () => {
// do something here ...
})
There are some examples of how to create the WebSocket server along with the HTTP server on ws npm page.
I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev
Currently I am writing a NS app that will communicate with a WebSocket over SSL. Here is server's code (server.js):
var fs = require('fs');
var cfg = {
port: 8082,
ssl_key: fs.readFileSync('keys/server.key'),
ssl_cert: fs.readFileSync('keys/server.crt'),
ca: fs.readFileSync('keys/ca.crt')
};
var httpServ = require('https');
var WebSocketServer = require('ws').Server;
var app = null;
// dummy request processing
var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};
app = httpServ.createServer({
// providing server with SSL key/cert
key: cfg.ssl_key,
cert: cfg.ssl_cert,
ca: cfg.ssl.ca,
passphrase: '1234',
requestCert: true,
rejectUnauthorized: false,
}, processRequest ).listen( cfg.port );
var wss = new WebSocketServer( { server: app } );
wss.on('connection', function(ws) {
console.log("Connected!");
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});
Server is running well without problem. Below is the client code (wsclient.js):
const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082');
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});
When I ran the client by typing node wsclient.js, it throw the following error:
Error: unable to verify the first certificate
Obviously, the error was caused by not providing the certificate info to the request. But I have no idea how to get this done in my client code. Thanks a lot for any clues or suggestions.
Finally I found the answer:
const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082',{
key: fs.readFileSync('./keys/client.key'),
cert: fs.readFileSync('./keys/client.crt'),
ca: fs.readFileSync('./keys/ca.crt')
});
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});
Now it works!
im trying to connect my client through web sockets in JS but I have this error
getUser.js:29 WebSocket connection to 'ws://localhost:8005/wsserver.js' failed: Connection closed before receiving a handshake response
But look my code:
getUser.js
var sock = new WebSocket("ws://localhost:8005/wsserver.js");
$('#data1').append("alors");
sock.onopen = function (event) {
$('#data').append("server status opened" + event.currentTarget.URL);
sock.send(JSON.stringify("coucou"));
console.log("sended");
};
sock.onmessage = function (event) {
$('#data').append(event.data);
console.log(event.data);
};
sock.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
And the server side code is:
wsserver.js
var WebSocketServer = require("ws").Server;
var ws = new WebSocketServer( { port: 8005 } );
console.log("Server started...");
ws.on('connection', function (ws) {
console.log("Browser connected online...")
ws.on("message", function (str) {
var ob = JSON.parse(str);
switch(ob.type) {
case 'text':
console.log("Received: " + ob.content)
ws.send('{ "type":"text", "content":"Server ready."}')
break;
case 'image':
console.log("Received: " + ob.content)
console.log("Here is an apricot...")
var path ="apricot.jpg";
var data = '{ "type":"image", "path":"' + path + '"}';
ws.send(data);
break;
}
})
ws.on("close", function() {
console.log("Browser gone.")
})
});
But the error is still here, i don't understand why
Take script part away from your client:
var sock = new WebSocket("ws://localhost:8005");
Server app is running in that port and all you need is to connect to the port.
I'm using the code below to test websockets on my browser:
this.webSocket = new WebSocket("ws://echo.websocket.org");
this.webSocket.onopen = function(evt) {
cc.log("Send Text WS was opened.");
};
this.webSocket.onmessage = function(evt) {
this.socketSendTextTimes++;
var textStr = "response text msg: " + evt.data + this.socketSendTextTimes;
cc.log(textStr);
};
The code works well, but if I connect to my own server running the code below:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req, res) {
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello!</h1>');
});
var socket = io.listen(server);
socket.set('destroy upgrade', false);
socket.on('connection', function(client) {
client.on('message', function(event) {
console.log('Received message from client!', event);
});
client.on('disconnect', function() {
console.log('Server has disconnected');
});
});
server.listen(8080);
console.log('start to listen');
My browser displays:
hello!
But the listening socket does not do anything. How can I connect to the Socket.IO server using websockets?
Socket.IO uses alternate transport methods than the native websocket, even when emulating websockets themselves. You will need the client library to connect to Socket.IO sockets.