Express路由文件中的Socket.io [英] Socket.io in Express routes file

查看:145
本文介绍了Express路由文件中的Socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个项目,该项目包括创建一个像鹅一样的游戏.为了做到这一点,我正在使用Node.js,Express,jade和现在的Socket.io.但是我遇到了一些麻烦,例如,将一个客户的职位分享给另一位客户.因为我的变量位置在index.js中的函数中,而且我不知道如何在路由文件中使用Socket.io.我尝试了一些事情,但没有任何效果.

I'm working on a project which consists in creating a game of the goose like. In order to do that, I'm using Node.js, Express, jade and now Socket.io. But I encounter some trouble, like, in example, to share the position of one client to the other client. Because my variable position is in a function in index.js and I don't know how I can use Socket.io in a route file. I try some things, but nothing works.

在Internet上,我见过一些人说在快速路由文件中使用Socket.io是没有意义的.那我该怎么办呢?

On internet, I've seen some people who say that there is no-sense to use Socket.io in an express route file. So how can I do that ?

在我的index.js中,我已经做到了:

In my index.js I've that :

exports.deplacement = function(io)
{
    return function(req,res)
    {
            //[...]
            io.sockets.on('connection', function(socket) 
        {
               socket.broadcast.emit('position', space);
        });
res.render('moteur' //[...]);
    }
}

在我的moteur.jade中,我已经做到了:

And in my moteur.jade I've done this :

 script(src="/socket.io/socket.io.js")
 script.
  var socket = io.connect('http://localhost:3000');
  socket.on('position ', function(space) {
    alert(space);
  })

推荐答案

首先,我不确定您的问题到底是什么意思,但是如果我认为是什么意思,那么我认为使用套接字是什么意思路由文件中的.io应该能够包含Node的socket.io模块提供的客户端javascript库.

First of all, I'm not sure what your question exactly means, but if it is what I think it is then I think what you mean by using socket.io in a route file is to be able to include the client side javascript lib provided with socket.io module of Node.

为此,您必须允许socket.io模块侦听服务器.这就像一个中间件本身.在将所有内容路由到服务器之前,所有内容都必须先通过socket.io.因此,当您请求客户端库时,它将被上传到客户端.

In order to do that, you have to allow the socket.io module to listen to server. This works like a middle-ware itself. Everything has to go through socket.io first before they are routed to the server. So, when you request the client side lib, it is uploaded to the client.

var express = require('express')
  , routes = require('./routes')
  , http = require('http');

var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server)

这篇关于Express路由文件中的Socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆