简体   繁体   English

如何使socket.io仅监听一条特定的路由?

[英]How to get socket.io to only listen on one specific route?

I'm only wanting socket.io to listen on my /home route but it seems to be listening on every route? 我只想让socket.io在/ home路由上侦听,但似乎在每条路由上侦听? Is there a way to get it only to listen to my /home route? 有没有办法让它只听我的/ home路由? This is what I have: 这就是我所拥有的:

const server = require('http').Server(app);
const io = require('socket.io')(server);

io.on('connection', function(socket){
  console.log('a user connected');
});

This is what I've tried, but this just displays a JSON file on the home path 这是我尝试过的方法,但这只会在主路径上显示一个JSON文件

const io = require('socket.io')(3000, {
  path: '/home',
  serveClient: true,
  // below are engine.IO options
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false
});

I'm only wanting socket.io to listen on my /home route but it seems to be listening on every route? 我只想让socket.io在/ home路由上侦听,但似乎在每条路由上侦听? Is there a way to get it only to listen to my /home route? 有没有办法让它只听我的/ home路由?

A client's Javascript either connects to the socket.io server or it doesn't - it's binary. 客户端的Javascript要么连接到socket.io服务器,要么没有连接-它是二进制的。 There's no use for multiple routes like there are with http requests. 没有多个路由可以使用,例如http请求。 socket.io supports connecting and listening for a particular namespace if you wanted multiple separate connection "channels" for multiple connections. 如果您想为多个连接使用多个单独的连接“通道”,socket.io支持连接和侦听特定的名称空间。

Ok so it just listens to everything on the site when the site is loaded? 好的,所以它只是在加载网站时监听网站上的所有内容? How do I only change things on one of my pages if it is listening to the whole site? 如果它正在监听整个网站,那么如何只更改其中一个页面上的内容? Or does that not slow things down? 还是这不会减慢速度?

A socket.io server just listens for incoming connections. socket.io服务器仅侦听传入的连接。 It is not associated with a route. 它与路线无关。

To have only some of your pages connect on socket.io, you either use different Javascript in some of your pages or you have your common Javascript check the path of the page and only connect on socket.io for specific page paths. 要只让您的某些页面在socket.io上连接,您可以在某些页面中使用不同的Javascript,或者让您的通用Javascript检查页面的路径,而仅在socket.io上连接特定的页面路径。

For example, you could have this in your web page Javascript: 例如,您可以在网页Javascript中使用它:

var socket;
if (window.location.pathname === "/home") {
     socket = io();
     socket.on(...);
}

This would allow your common Javascript (that is present in many pages) to only create a socket.io connection in your /home page. 这将使您的通用Javascript(存在于许多页面中)只能在/home页面中创建一个socket.io连接。

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

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