Help! Run ws on the same port as a http Express?
m2kar opened this issue · 2 comments
m2kar commented
How to run ws on the same port as a http Express?
I tried the example express-session-parse
given by ws
(link), and replace the const { WebSocketServer } = require('ws');
to const WebSocketServer = require('rpc-websockets').Server;
, and add a hello
remote function, but it didn't work. The client has no output, the server output is only Parsing session from request..
.
What need I do?
The source code of server and client are :
server
// server: index.json
'use strict';
const session = require('express-session');
const express = require('express');
const http = require('http');
const uuid = require('uuid');
const WebSocketServer = require('rpc-websockets').Server;
const app = express();
const map = new Map();
//
// We need the same instance of the session parser in express and
// WebSocket server.
//
const sessionParser = session({
saveUninitialized: false,
secret: '$eCuRiTy',
resave: false
});
//
// Serve static files from the 'public' folder.
//
app.use(express.static('public'));
app.use(sessionParser);
app.post('/login', function (req, res) {
//
// "Log in" user and set userId to session.
//
const id = uuid.v4();
console.log(`Updating session for user ${id}`);
req.session.userId = id;
res.send({ result: 'OK', message: 'Session updated' });
});
app.delete('/logout', function (request, response) {
const ws = map.get(request.session.userId);
console.log('Destroying session');
request.session.destroy(function () {
if (ws) ws.close();
response.send({ result: 'OK', message: 'Session destroyed' });
});
});
//
// Create an HTTP server.
//
const server = http.createServer(app);
//
// Create a WebSocket server completely detached from the HTTP server.
//
const wss = new WebSocketServer({ clientTracking: false, noServer: true });
server.on('upgrade', function (request, socket, head) {
console.log('Parsing session from request...');
sessionParser(request, {}, () => {
if (!request.session.userId) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
console.log('Session is parsed!');
wss.handleUpgrade(request, socket, head, function (ws) {
wss.emit('connection', ws, request);
});
});
});
wss.on('listening',()=>{
wss.register('hello',({index})=>{
console.log(index);
return `index:${index}`;
})
})
wss.on('connection', function (ws, request) {
const userId = request.session.userId;
map.set(userId, ws);
ws.on('message', function (message) {
//
// Here we can now use session parameters.
//
console.log(`Received message ${message} from user ${userId}`);
});
ws.on('close', function () {
map.delete(userId);
});
});
//
// Start the server.
//
server.listen(8082, function () {
console.log('Listening on http://localhost:8082');
});
client
// client: rpc_client.js
const WebSocket = require('rpc-websockets').Client;
// instantiate Client and connect to an RPC server
const ws = new WebSocket('ws://localhost:8082/');
ws.on('open', function () {
console.log("connected");
ws.call("hello",{index},).then((ret)=>{
console.log(ret);
}).catch(err=>{
console.trace(err);
})
});
jumo-sballing commented
Don't know if this helps but I pass the express server straight to the WebsocketServer. This works fine.
//
// Create an HTTP server.
//
const server = http.createServer(app);
//
// Create a WebSocket server and pass the express webserver.
//
const wss = new WebSocketServer({ server });
wss.on('connection', (socket, request) => {
console.log('ws client connected, ' + socket._id + ', ' + request.url);
});