Reputation: 363
I am wondering if the server implementation in the ws library allows to find out, which connected client triggered a message event. I am hoping I can avoid to dive into the code to find out...
Thanks!
P.S.: I am aware of the FAQ: How to get the IP address of the client?, but that refers to the situation of a new connection. I am interested in the event of an incoming message.
Upvotes: 1
Views: 2427
Reputation: 363
Wait, never mind - I figured it out. It is actually pretty obvious.
When you define the closure that deals with a message for a websocket ws
, you have to be in a context where ws is defined - i.e., the closure of the websocket server wss
's on
-function for the 'connection' event. And there you also have access to the request object req
that gives you the remote address:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws, req) {
console.log('connected: '+req.connection.remoteAddress);
ws.on('message', function incoming(message) {
console.log('received from %s: %s', req.connection.remoteAddress, message);
// do stuff with the message
});
});
Upvotes: 1