Skip to content

Instantly share code, notes, and snippets.

@RanjanSushant
Last active November 25, 2021 05:39
Show Gist options
  • Save RanjanSushant/a5f59597c7d68e366d18afcd665aabe5 to your computer and use it in GitHub Desktop.
Save RanjanSushant/a5f59597c7d68e366d18afcd665aabe5 to your computer and use it in GitHub Desktop.
//Websocekt variables
const url = "ws://localhost:9876/myWebsocket"
const mywsServer = new WebSocket(url)
//DOM Elements
const myMessages = document.getElementById("messages")
const myInput = document.getElementById("message")
const sendBtn = document.getElementById("send")
sendBtn.disabled = true
sendBtn.addEventListener("click", sendMsg, false)
//Sending message from client
function sendMsg() {
const text = myInput.value
msgGeneration(text, "Client")
mywsServer.send(text)
}
//Creating DOM element to show received messages on browser page
function msgGeneration(msg, from) {
const newMessage = document.createElement("h5")
newMessage.innerText = `${from} says: ${msg}`
myMessages.appendChild(newMessage)
}
//enabling send message when connection is open
mywsServer.onopen = function() {
sendBtn.disabled = false
}
//handling message event
mywsServer.onmessage = function(event) {
const { data } = event
msgGeneration(data, "Server")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment