Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created June 30, 2025 02:35
Show Gist options
  • Save ProfAvery/9cf53a6075fa0d7f7b7789d4621448d2 to your computer and use it in GitHub Desktop.
Save ProfAvery/9cf53a6075fa0d7f7b7789d4621448d2 to your computer and use it in GitHub Desktop.
/* global WebSocket */
const socket = new WebSocket('ws://localhost:8080')
// send message from the form
document.forms.publish.onsubmit = function () {
const outgoingMessage = this.message.value
socket.send(outgoingMessage)
return false
}
// message received - show the message in div#messages
socket.onmessage = async function (event) {
const message = await event.data.text()
const messageElem = document.createElement('div')
messageElem.textContent = message
console.log(message)
document.getElementById('messages').prepend(messageElem)
}
<!-- message form -->
<form name="publish">
<input type="text" name="message">
<input type="submit" value="Send">
</form>
<!-- div with messages -->
<div id="messages"></div>
<script src="client.js"></script>
{
"scripts": {
"start": "npm-run-all --parallel frontend backend",
"backend": "nodemon --ignore client.js server.js",
"frontend": "browser-sync start --server --files \"*.html,client.js\"",
"test": "standard --fix"
},
"type": "module",
"dependencies": {
"ws": "^8.18.3"
},
"devDependencies": {
"browser-sync": "^3.0.4",
"nodemon": "^3.1.10",
"npm-run-all": "^4.1.5",
"standard": "^17.1.2"
}
}
import { WebSocketServer } from 'ws'
const wss = new WebSocketServer({ port: 8080 })
const clients = new Set()
wss.on('connection', onSocketConnect)
function onSocketConnect (ws) {
clients.add(ws)
ws.on('message', function (message) {
message = message.slice(0, 50) // max message length will be 50
for (const client of clients) {
client.send(message)
}
})
ws.on('close', function () {
clients.delete(ws)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment