redweb 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/SocketServer.js +14 -9
- package/package.json +1 -1
package/SocketServer.js
CHANGED
|
@@ -21,7 +21,7 @@ const SOCKET_OPTIONS = {
|
|
|
21
21
|
connectionCloseCallback: undefined,
|
|
22
22
|
messageCallback: undefined,
|
|
23
23
|
messageHandlers: {
|
|
24
|
-
'ping': (
|
|
24
|
+
'ping': function(data) { this.send(JSON.stringify({ type: 'pong' })); }
|
|
25
25
|
},
|
|
26
26
|
ssl: null
|
|
27
27
|
};
|
|
@@ -33,34 +33,39 @@ const SOCKET_OPTIONS = {
|
|
|
33
33
|
*/
|
|
34
34
|
function BaseSocketServer(server, options = {}) {
|
|
35
35
|
this.wss = new WebSocket.Server({ server });
|
|
36
|
+
this.clients = new Map(); // Use a Map to store clients by their IP addresses
|
|
36
37
|
Object.assign(this, { ...SOCKET_OPTIONS, ...options });
|
|
37
38
|
|
|
38
|
-
this.wss.on('connection', (socket) => {
|
|
39
|
-
|
|
39
|
+
this.wss.on('connection', (socket, req) => {
|
|
40
|
+
const ip = req.socket.remoteAddress;
|
|
41
|
+
console.log(`New client connected: ${ip}`);
|
|
42
|
+
this.clients.set(ip, socket);
|
|
43
|
+
|
|
40
44
|
if (this.connectionOpenCallback) this.connectionOpenCallback(socket);
|
|
41
45
|
|
|
42
46
|
socket.on('message', (message) => {
|
|
43
47
|
try {
|
|
44
|
-
console.info(`Received message: ${message}`);
|
|
45
|
-
if (this.messageCallback) this.messageCallback(message);
|
|
48
|
+
console.info(`Received message from ${ip}: ${message}`);
|
|
49
|
+
if (this.messageCallback) this.messageCallback(socket, message);
|
|
46
50
|
const parsedMessage = JSON.parse(message);
|
|
47
51
|
const { type, data } = parsedMessage;
|
|
48
52
|
|
|
49
53
|
if (this.messageHandlers[type]) {
|
|
50
|
-
this.messageHandlers[type](data);
|
|
54
|
+
this.messageHandlers[type].call(socket, data);
|
|
51
55
|
}
|
|
52
56
|
} catch (error) {
|
|
53
|
-
console.error(
|
|
57
|
+
console.error(`Error handling message from ${ip}:`, error);
|
|
54
58
|
}
|
|
55
59
|
});
|
|
56
60
|
|
|
57
61
|
socket.on('close', () => {
|
|
58
|
-
console.log(
|
|
62
|
+
console.log(`Client disconnected: ${ip}`);
|
|
63
|
+
this.clients.delete(ip);
|
|
59
64
|
if (this.connectionCloseCallback) this.connectionCloseCallback(socket);
|
|
60
65
|
});
|
|
61
66
|
|
|
62
67
|
socket.on('error', (error) => {
|
|
63
|
-
console.error(
|
|
68
|
+
console.error(`Socket error from ${ip}:`, error);
|
|
64
69
|
});
|
|
65
70
|
});
|
|
66
71
|
|