Last active
November 25, 2021 05:39
-
-
Save RanjanSushant/a5f59597c7d68e366d18afcd665aabe5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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