html5 - express4 + socket.io 如何在connection的回调外边使用socket.emit方法
ringa_lee
ringa_lee 2017-04-17 16:09:00
0
5
593

app.js

    var sockect = require('./socket/server')
    var users = require('../router/users')
    
    app.use('/users', users); //路由
    
    var server = app.listen(9000, function () {
        console.log('server start');
    });
    
    sockect(server); //启动socket

server.js

'use strict';

module.exports = function(server) {
    var io = require('socket.io').listen(server);
    io.sockets.on('connection', function (socket) {
        //如何将这里的socket暴露给其他地方的js方法里使用socket.emit ?
    });
    return io;

};

上面是我目前的结构,希望在users里面的逻辑里触发emit方法,google了很多,也没有找到有什么办法可以将参数socket传递出去,不然的话所有逻辑只要涉及到socket.emit的都要写在connection的回调里..

ringa_lee
ringa_lee

ringa_lee

reply all(5)
黄舟

In the server.js file:

var users = require('../router/users')
module.exports = function(server) {
    var io = require('socket.io').listen(server);
    io.sockets.on('connection', function (socket) {
        //如何将这里的socket暴露给其他地方的js方法里使用socket.emit ?
        users.doSomething(socket);
    });
    return io;

};

Then write business logic in users.js

巴扎黑

I also encountered this problem, please solve it

大家讲道理

I also think that within the scope of external calls socket没什么意义。。
而且expresssocket两者走的协议都不一样,
你可以把user的身份信息保存在 局部变量socket
use identification information to perform corresponding user operations

大家讲道理

Same question, how to expose the socket object? ? ? ?

巴扎黑
<table width="160" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
   <td width="165" height="32"><img src="images/tell_top.gif" width="165" height="32" border="0"></td>
     </tr>
     <tr>
      <td height="52" background="images/tell_center.gif">
       <?php
          include_once("function.php");
          $news="明日编程词典上市了!";
          $i=1;
          do{
          ?>
       <table with="148" height="25" border="0" align="center" cellpadding="0" cellspacing="0">
         <tr>
          <td width="17" height="20"><img src="images/mark_0.gif" width="0" height="10"></td>
          <td width="333">
          <?php
           echo chinesesubstr($news, 0, 18);
           if(strlen($nes)>18){
               echo "...";
           }
          ?> 
          </td>
         </tr>
        <tr>
          <td height="5"></td>
          <td height="5" background="images/back_point_write.gif"></td>
        </tr>
      </table>
        <?php
        $i++;
        }while($i<=5);
        ?>
        </td>
     </tr>
     <tr>
      <td width="165" height="12"><img src="images/tell_bottom.gif" width="165" height="12"></td>
     </tr>
     </table>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template