I aspire to assign Websockets and net.Sockets with unique identifiers, so when a message is received, the client is identified by the identifier attached to the socket.
Previous research:
For Websocket:
According to this and this, the following is requires:
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.id = uuid.v4(); // This is the relevant line of code
ws.on('message', (msg: string) => {
...
}
});
For net.Socket:
Quite the same - according to this, the following is required:
var server = net.createServer();
server.on('connection', function(conn) {
conn.id = uuid.v4(); // This is the relevant line of code
conn.on('data', function(data) {
...
});
});
The problem
The error "Property 'id' does not exist on type 'WebSocket' [or 'Socket' accordingly]" during compilation. This explains why.
Optional Solution #1: Cast to any
The update net.Socket code will be:
var server = net.createServer();
server.on('connection', function(conn) {
(conn as any).id = uuid.v4();
conn.on('data', function(data) {
console.log('Session id:' + (conn as any).id);
});
});
The problem: It doesn't seem like good practice to me. I don't have references for why except for a hunch for now.
Optional Solution #2: Use a local variable [seems like a better option]
The update net.Socket code will be:
var server = net.createServer();
server.on('connection', function(conn) {
const id: string = uuid.v4();
conn.on('data', function(data) {
console.log('Session id:' + id);
});
});
After some experiencing, it seems to work properly.
So - the questions:
- In optional solution #2: is it guaranteed that the id variable will always be available in this scope? In other words: is this solution valid? for both net.Socket & Websocket? Or is there something that I'm missing?
- In general: Is there additional identifiers (perhaps built in identifiers in WebSocket and net.Socket) that can be used instead?
[Typescript version: 3.2.4].
from Assigning WebSocket and net.Socket with unique id [Typescriprt]
No comments:
Post a Comment