How to use web socket


  • Create a new WebSockets connection
  const url = 'wss://yoursite/action'  
  const connection = new WebSocket(url)
  
Method of WebSocket object

  • onopen

When the connection is successfully established, the open event is fired.
Listen for it by assigning a callback function to the onopen property of the connection object:

connection.onopen = () => {
  //...
}
  •  onerror
If there’s any error, the onerror function callback is fired:

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)
}
  • Send
Sending data to the server using WebSockets. Once the connection is open, you can send data to the server.You can do so conveniently inside the onopen callback function:

connection.onopen = () => {
  connection.send('hey')
}
  • Receive
Receiving data from the server using WebSockets.  Listen with a callback function on onmessage, which is called when the message event is received:

connection.onmessage = e => {
  console.log(e.data)}
}

Comments

Popular Posts