Home > Software engineering >  WebSocket send data to server on initial request
WebSocket send data to server on initial request

Time:10-16

So like the title is saying at the first request the client does, i want to send the client id to the server.

var userId = "userId"; var ws = new WebSocket("wss://serveradress?clientId")

Is there anyway to pass the data on the initial request via query string or something.

Appreciate every idea, thank you!

CodePudding user response:

wss.on('request', (e)=>{
  console.log(e.userId);
})

On the server site i have the code like this but i get an undefined.

CodePudding user response:

As per the docs you can call the websocket onopen method. Then in the callback use the websocket send method to send data

websocket.onopen = function() {
   websocket.send(your data)
}

To accept the incoming message server side just accept the request. This is assuming you are using websocket-node

ws.on('request', (request) => {
  const conn = request.accept('echo-protocol', request.origin)
  conn.on('message', (message) => {
     console.log(message)
  })
})

If you are using this package then just listen for the 'message' event.

ws.on('message', (message) => {
  console.log(message)
})
  • Related