Biliothek:ws
Version vom 6. März 2018, 14:25 Uhr von Admin (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „Category:Bibliothek == Server == (Teilweise übernommen aus [https://github.com/websockets/ws]) === Server bereitstellen === <syntaxhighlight lang="Java…“)
Inhaltsverzeichnis
Server
(Teilweise übernommen aus [1])
Server bereitstellen
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
Sending and receiving text data
var WebSocket = require('ws');
var ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function(data, flags) {
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
});
Server sending broadcast data
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
client.send(data);
});
};
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
// Broadcast to everyone except message sending socket
wss.clients.forEach(function each(client) {
if (client !== ws) client.send(data);
});
});
});