简体   繁体   English

用socket.io路由

[英]Routing with socket.io

I'm writing an express app.js with socket.io, and came across a problem. 我正在用socket.io写一个快速的app.js,遇到一个问题。
I can't figure out how to use the routes. 我不知道如何使用路线。 I want the client to write for example localhost:3000/?id=3 and get something according to the id. 我希望客户端编写例如localhost:3000/?id=3并根据ID得到一些信息。 But in the socket.io connection event I dont know the url or the params (or is there a way?) 但是在socket.io连接事件中,我不知道url或params(或者有办法吗?)

io.on('connection', function (socket) {/*should be something according to the id in the url*/});

untill now I just checked the id with 直到现在我才用

app.get('/', function (req, res) {
    //req.query.id
});

Anyone knows a way around this? 有人知道解决这个问题的方法吗?

Thank you! 谢谢!

It appears you may be a bit confused about how you use webSockets. 您似乎对使用webSockets有点困惑。 If you want to make an http request such as localhost:3000/?id=3 , then you don't use webSockets. 如果要发出诸如localhost:3000/?id=3类的http请求,则不要使用webSockets。 You use the normal routing mechanisms in Express. 您使用Express中的常规路由机制。

A webSocket connection is created and then persists. 将创建一个webSocket连接,然后持久连接。 From then on, you define messages with optional data as arguments for those messages and you can send these messages either direction on the webSocket. 从那时起,您可以将带有可选数据的消息定义为这些消息的参数,并且可以在webSocket上向任一方向发送这些消息。 webSocket messages are sent on an existing webSocket, not to a URL. webSocket消息是通过现有的webSocket发送的,而不是通过URL发送的。 You could create a message for sending URLs from client to server if you wanted. 如果需要,您可以创建一条消息,用于从客户端向服务器发送URL。 If that was the case, you could do this in the client: 如果是这种情况,您可以在客户端中执行以下操作:

socket.emit("sendURL", url);

And, then you would listen for the "sendURL" message on the server. 然后,您将在服务器上侦听"sendURL"消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM