给 socket.io 添加一个自定义属性,并在服务器中获取这个值

Add a custom attribute to socket.io and get this value in the server

我正在尝试在客户端将 属性 扩展到我的 socket.io,使用自定义值,例如:

var socket = io(); socket.customAttr = "123"

并在节点服务器中获取此值,但我在客户端扩展此功能,但在服务器中始终是 undefinded

有一种方法可以将 customAttributes 添加到我的 socket.io?

对于为这个老问题找到解决方案的人:现在(v4.x)你可以使用socket.handshake.query。 客户:

import { io } from "socket.io-client"; 
const socket = io({ query: { x: 42 } });

服务器:

io.on("connection", (socket) => { 
console.log(socket.handshake.query); // prints { x: "42"} 
});