1.10.32. fejezet, WebSocket

Kapcsolódó hivatkozások

Telepítés

npm install ws
npm install --save-dev @types/ws

Szerver

import WebSocket from 'ws';
 
const wss = new WebSocket.Server({ port: 8080 });
 
wss.on('connection', (ws: WebSocket) => {
  console.log('New client connected');
 
  ws.on('message', (message: string) => {
    console.log(`Received message: ${message}`);
    ws.send(`Server received your message: ${message}`);
  });
 
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

Kliens

import WebSocket from 'ws';
 
const ws = new WebSocket('ws://localhost:8080');
 
ws.on('open', () => {
  console.log('Connected to server');
 
  ws.send('Hello, server!');
});
 
ws.on('message', (message: string) => {
  console.log(`Received message from server: ${message}`);
});
 
ws.on('close', () => {
  console.log('Disconnected from server');
});

Böngésző kliens

<html>
	<head>
		<title>WebSocket Home</title>
	</head>
	<script>
		function send() {
			var ws = new WebSocket("ws://localhost:8080");
			ws.onopen = function () {
				ws.send("Hello, world");
			};
			ws.onmessage = function (evt) {
				alert(evt.data);
			};
			ws.onclose = function () {
				alert("closed");
			};
		}
	</script>
	<body>
		<button onclick="send()">Send</button>
	</body>
</html>

HTTPS websocket szerver

const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
 
const server = new https.createServer({
    cert: fs.readFileSync('/etc/letsencrypt/live/{host}/fullchain.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/{host}/privkey.pem')
});
const wss = new WebSocket.Server({ server });
var msg;
 
wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        msg = message;
        console.log('received: %s', msg);
        wss.clients.forEach(function (client) {
            if (client.readyState == WebSocket.OPEN) {
                client.send(msg);
            }
        });
    });
 
    ws.send('Chat room is working!');
});
 
server.listen(8082);

Figyelem! A WebSocket kliens nem kapcsolódik érvénytelen vagy Self-Signed aláírással rendelkező szerverre.

var ws = new WebSocket("wss://myserver.hu:8082");