Created
March 29, 2024 15:19
-
-
Save RealYukiSan/1fa982284f71afcb39d8eebd7602bfb7 to your computer and use it in GitHub Desktop.
Tried simple websocket communication
This file contains 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 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]'); | |
} |
This file contains 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 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); |
This file contains 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 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