Skip to content

Instantly share code, notes, and snippets.

@RealYukiSan
Created March 29, 2024 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RealYukiSan/1fa982284f71afcb39d8eebd7602bfb7 to your computer and use it in GitHub Desktop.
Save RealYukiSan/1fa982284f71afcb39d8eebd7602bfb7 to your computer and use it in GitHub Desktop.
Tried simple websocket communication
const socket = new WebSocket("ws://localhost:8080")
socket.onopen = function (e) {
alert('[open] connection established')
alert('sending data to server')
socket.send('My name is who am i?');
}
socket.onmessage = function (ev) {
alert(`[message] data received from srv: ${ev.data}`);
};
socket.onclose = function (ev) {
if (ev.wasClean) {
alert(`[close] connection closed cleanly, code=${ev.code} reason=${ev.reason}`)
} else {
alert('[close] connection died');
}
}
socket.onerror = function (err) {
alert('[error]');
}
const http = require("http")
const ws = require("ws")
const wss = new ws.Server({ noServer: true })
function accept(req, res) {
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect)
}
function onConnect(ws) {
ws.on('message', function (message) {
message = message.toString()
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu)
ws.send(`Hello from server ${name}!`)
setTimeout(() => ws.close(1000, "Bye!"), 5000);
})
}
http.createServer(accept).listen(8080);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>Hemlo</h1>
<script src="./client.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment