1.10.5.4. fejezet, WebSocket

WebSocket szerver

Minta kód egy WebSocket chat szerverre:

const fs = require('fs');
const WebSocket = require('ws');
const url = require('url');
 
/*
const https = require('https');
 
const server = new https.createServer({
    cert: fs.readFileSync('cert.pem'), //fullchain
    key: fs.readFileSync('key.pem') //privkey
});
//*/
//*
const http = require('http');
const server = new http.createServer();
//*/
 
const wss = new WebSocket.Server({ server });
var msg;
var clients = new Set();
 
wss.on('connection', function connection(ws, req) {
    clients.add(ws);
    const parameters = url.parse(req.url, true);
    console.log("Params: ", JSON.stringify(parameters));
    console.log("Client:", parameters.query.client);
    console.log("Auth header:", req.headers.authorization);
    ws.userName = parameters.query.client;
    ws.on('message', function incoming(message) {
        msg = message;
        console.log('received: %s', msg);
        wss.clients.forEach(function (client) {
            if (client != ws && client.readyState == WebSocket.OPEN) {
                client.send(ws.userName + ": " + msg);
            }
        });
    });
    ws.on('close', function () {
        clients.delete(ws);
        console.log('disconnected');
    });
 
    ws.send('Hello ' + ws.userName + '! Chat room is working.');
});
 
server.listen(8082);

Websocket kliens

Böngészőben működő minta WebSocket kliensre:

<!doctype html>
<html>
<head>
<style>
    textarea { vertical-align: bottom; }
    #output { overflow: auto; }
    #output > p { overflow-wrap: break-word; }
    #output span { color: blue; }
    #output span.error { color: red; }
</style>
</head>
<body>
<h2>WebSocket Test</h2>
<textarea cols=60 rows=6>
<html><body><div id="cert"></div></body></html>
</textarea>
<button>send</button>
<div id=output></div>
<script>
 
    var button = document.querySelector("button"),
        output = document.querySelector("#output"),
        textarea = document.querySelector("textarea"),
 
        wsUri = "wss://exprog.hu:8082/",
        websocket = new WebSocket(wsUri);
 
    button.addEventListener("click", onClickButton);
 
    websocket.onopen = function (e) {
        writeToScreen("CONNECTED");
    };
 
    websocket.onclose = function (e) {
        writeToScreen("DISCONNECTED");
    };
 
    websocket.onmessage = function (e) {
        if (e.data instanceof Blob) {
          reader = new FileReader();
          reader.onload = () => {        
            writeToScreen("<span>RESPONSE: " + reader.result + "</span>");
          }
          reader.readAsText(e.data);
        } else {
          writeToScreen("<span>RESPONSE: " + e.data + "</span>");
        }
    };
 
    websocket.onerror = function (e) {
        writeToScreen("<span class=error>ERROR:</span> " + e.data);
    };
 
    function doSend(message) {
        writeToScreen("SENT: " + message);
        websocket.send(message);
    }
 
    function writeToScreen(message) {
        output.insertAdjacentHTML("afterbegin", "<p>" + message + "</p>");
    }
 
    function onClickButton() {
		var jsonShowMsg = textarea.value;
		doSend(jsonShowMsg);
        textarea.value = "";
        textarea.focus();
    }
</script>
</body>
</html>