Last active
April 25, 2023 23:50
-
-
Save IzzleNizzle/b6220b984b9d7d3c57abb56697698c03 to your computer and use it in GitHub Desktop.
This example demonstrates how to create a simple web application using WebSockets to establish real-time communication between a server and a client, allowing messages to be sent and received in real-time.
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
<!doctype html> | |
<html> | |
<head> | |
<title>WebSocket Test</title> | |
</head> | |
<body> | |
<div> | |
<button id="button1">Button 1</button> | |
<button id="button2">Button 2</button> | |
</div> | |
<script> | |
var ws = new WebSocket('ws://localhost:8082/'); | |
// Send message when button is clicked | |
var button1 = document.getElementById('button1'); | |
button1.onclick = function() { | |
ws.send('Button 1 was clicked'); | |
}; | |
var button2 = document.getElementById('button2'); | |
button2.onclick = function() { | |
ws.send('Button 2 was clicked'); | |
}; | |
// Log messages from the server | |
ws.onmessage = async function (event) { | |
var text = await event.data.text() | |
console.log(text); | |
}; | |
</script> | |
</body> | |
</html> |
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
{ | |
"name": "server", | |
"version": "1.0.0", | |
"description": "", | |
"main": "server.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"start": "node server.js" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"ws": "^8.11.0" | |
} | |
} |
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
const WebSocket = require('ws'); | |
const wss = new WebSocket.Server({ port: process.env.WEBSOCKET_PORT || 8082 }); | |
wss.on('connection', function connection(ws) { | |
ws.on('message', function incoming(message) { | |
console.log('received: %s', message); | |
// Broadcast to all clients | |
wss.clients.forEach(function each(client) { | |
if (client.readyState === WebSocket.OPEN) { | |
client.send(message); | |
} | |
}); | |
}); | |
}); |
Author
IzzleNizzle
commented
Apr 25, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment