This repository has been archived by the owner on Aug 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
WebSocketServer.js
58 lines (52 loc) · 1.65 KB
/
WebSocketServer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) 2017, Intel Corporation.
// Sample for "ws" module implementing a Web Socket server.
// To run it on the Arduino 101, you'll need to first connect via BLE then
// add the IP route for the Arduino's 6lowpan address
//
// ip -6 route add 2001:db8::/64 dev bt0
//
// Then you can use a websocket client samples/websockets/NodeWebsocketClient.js
// to connect and interact with the server.
console.log("WebSocketServer sample...");
var WebSocket = require('ws');
var wss = new WebSocket.Server({
port: 8080,
acceptHandler: function(protos) {
for (var i = 0; i < protos.length; i++) {
if (protos[i] == "my_ws_protocol") {
return protos[i];
}
}
return false;
}
});
var count = 0;
var t = null;
wss.on('connection', function(ws) {
console.log("CONNECTION");
ws.on('message', function(message) {
console.log("MESSAGE: " + message.toString('ascii'));
t = setTimeout(function() {
ws.send(new Buffer("Message #" + count), true);
if (count % 10 == 0) {
ws.ping(new Buffer("PING"));
}
count++;
}, 100);
});
ws.on('ping', function(data) {
console.log("PING: " + data.toString('ascii'));
ws.pong(data);
});
ws.on('pong', function(data) {
console.log("PONG: " + data.toString('ascii'));
});
ws.on('close', function(code, reason) {
console.log("close event: " + reason + " code: " + code);
clearTimeout(t);
});
ws.on('error', function(error) {
console.log(error.name + " : " + error.message);
clearTimeout(t);
});
});