“JavaScript WebSocket -Beispielcode” Code-Antworten

Websocket -Beispielcode 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))
Lucky Lion

JavaScript WebSocket -Beispielcode

var Socket = new WebSocket('ws://' + window.location.hostname + ':81/'); // The '81' here is the Port where the WebSocket server will communicate with
// The instance of the WebSocket() class (i.e. Socket here), must need to be globally defined

Socket.send("pass your data here, and it'll be String"); // This method one can call locally
Pritam Pagla

Ähnliche Antworten wie “JavaScript WebSocket -Beispielcode”

Fragen ähnlich wie “JavaScript WebSocket -Beispielcode”

Weitere verwandte Antworten zu “JavaScript WebSocket -Beispielcode” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen