on the client i'm having
ws.onopen = () => {
ws.send(JSON.stringify([
{uid: 7, name: 'John'} // persistent data
]))
};
then on the server, i'm storing connections inside connections array
var connections = []
wss.on('connection', function connection(ws) {
var id = ws.upgradeReq.headers['sec-websocket-key'];
connections.push(id);
}
but i don't know how i could get data object send by the client at onconnection in order to create an object like
connections = [{wsId: '2JL30', uid: 7, name: 'Johtn'}]
You can use a query string, like this:
const ws = new WebSocket('ws://example.com/?id=2JL30&uid=7&name=Johtn');
then you can parse the query string in the connection listener:
wss.on('connection', (ws) => {
const data = url.parse(ws.upgradeReq.url, true).query;
});
thank you, but i ended in this workaround
var connections = []
var id;
var connectionIndex = (id) => connections.findIndex(el => el.wsId === id);
wss.on('connection', function connection(ws) {
id = ws.upgradeReq.headers['sec-websocket-key'];
connections.push({wsId: id});
ws.on('close', function() {
log('Disconnected: uid: %s, role: %s',connections[connectionIndex(id)].uid)
log(connections)
});
ws.on('message', function(response) {
var r = JSON.parse(response),
payload = r.payload;
switch(r.type) {
case "join":
connections[connectionIndex(id)].uid = payload.uid;
connections[connectionIndex(id)].role = payload.role;
connections[connectionIndex(id)].name = payload.name;
console.log('%s joined the game as a %s, having id %s',
console.log(connections)
break;
default:
console.log("msg: %s", r);
}
});
});
and on the cliend i'm sending the data
var S = (type, payload) => ws.send(JSON.stringify({
type: type,
payload: payload
}));
ws.onopen = () => s('join', [{data}])
Whatever works better for you :)
;) thank you
Most helpful comment
You can use a query string, like this:
then you can parse the query string in the
connectionlistener: