JSFiddle - React, Tailwind, and code Playground

by ruyi

HTML

<input id="msg">
<button id="w2send" onclick="sendMsg()">
ws2 send
</button>
<div>
All the messages ws1 received will be below here:
</div>
<div id="messages">

</div>

JavaScript

const wsUrl = 'wss://test.ws.myws.dev'
const connectionUrl1 = wsUrl + '/?token=w1'
const connectionUrl2 = wsUrl + '/?token=w2'
const ws1 = new WebSocket(connectionUrl1)
const ws2 = new WebSocket(connectionUrl2)
const messages = document.getElementById('messages')

const sendMsg = () => {
	const msg = document.getElementById('msg').value
  ws2.send(JSON.stringify({
    action: 'pub',
    topic: 'a-random-topic',
    message: {
      body: msg,
      otherField: 'any field or value you like'
    }
  }))
  document.getElementById('msg').value=''
}

ws1.addEventListener('open', ()=>{
	console.log('ws1 connected')
  ws1.send(JSON.stringify({
    action: 'ping'
  }))
  ws1.send(JSON.stringify({
    action: 'sub',
    topic: 'a-random-topic'
  }))
})

ws1.addEventListener('message', (m)=>{
  const data = JSON.parse(m.data)
	console.log(data)
  if(data.message?.body) {
  	messages.innerHTML += data.from + ': ' + 
    data.message.body + '<br />'
  }
})

ws2.addEventListener('open', ()=>{
	console.log('ws2 connected')
  ws2.send(JSON.stringify({
    action: 'sub',
    topic: 'a-random-topic'
  }))
  setTimeout(()=>{
  	console.log('sending pub msg')
  	ws2.send(JSON.stringify({
      action: 'pub',
      topic: 'a-random-topic',
      message: {
        body: 'some text messages',
        otherField: 'any field or value you like'
      }
    }))
  }, 1000)
  
})