Ws: passing data to on('connection')

Created on 6 Nov 2016  路  4Comments  路  Source: websockets/ws

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'}]

Most helpful comment

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;
});

All 4 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brainkim picture brainkim  路  4Comments

nabeelio picture nabeelio  路  5Comments

quesurifn picture quesurifn  路  3Comments

dcflow picture dcflow  路  4Comments

bartosz-m picture bartosz-m  路  3Comments