Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

websocket sample code js

/*
 * Link starts with ws:// or wss://
 * ws:// for non ssl
 * wss:// for ssl
*/
let ws = new WebSocket('LINK_HERE')
        
ws.addEventListener('open', function (event) {
  //WebSocket Connected
  console.log('connected')
})

ws.addEventListener('message', function (event) {
  //Received message
  console.log('MESSAGE RECEIVED')
  console.log(event.data) //MESSAGE DATA
})

ws.addEventListener('close', function (event) {
  //WebSocket disconnected
  console.log('disconnected')
})

// To send data
ws.send('hello')

// Only text formats allowed to send, if data is in json format use
ws.send(JSON.stringify(object))
 
PREVIOUS NEXT
Tagged: #websocket #sample #code #js
ADD COMMENT
Topic
Name
9+2 =