egg-socket.io不能主动给客户端发送请求吗

Created on 13 Nov 2017  ·  6Comments  ·  Source: eggjs/egg

  • Node Version:
  • Egg Version:
  • Plugin Name:
  • Plugin Version:
  • Platform:
  • Mini Showcase Repository:

Most helpful comment

我的问题 其实是 不能在服务器主动触发的情况下给客户端发送数据包吗 , 只能被动发送吗 就是客户端发送消息到服务端的时候服务端才能处理 ?不能服务端主动触发吗

All 6 comments

如果想主动发消息给客户端,可以使用 socket.io-emitter

@ngot 催文档啦~

连接建立以后,通过 client {socket.id} 可以只向该 client 发送消息,下面是 WebRTC Demo 部分代码

服务端

// {appRoot}/app/router.js

'use strict';

module.exports = app => {
  app.get('/', 'home.index');
  app.io.of('/webrtc').route('exchange', app.io.controllers.exchange);
};
// {appRoot}/app/extend/helper.js

'use strict';

module.exports = {
  parseMsg(action, payload, metadata = {}) {
    // this 是 helper 对象,在其中可以调用其他 helper 方法
    // this.ctx => context 对象
    // this.app => application 对象
    const meta = Object.assign({}, {
      timestamp: Date.now(),
    }, metadata);
    return {
      meta,
      data: {
        action,
        payload,
      },
    };
  },
};
// {appRoot}/app/io/controller/exchange.js

'use strict';

module.exports = () => {
  return function* () {
    const message = this.args[ 0 ] || {};
    const client = this.socket.id;
    try {
      const { target, payload } = message;
      if (!target) {
        return;
      }
      const msg = this.helper.parseMsg('exchange', payload, {
        client,
        target,
      });
      this.app.io.of('/webrtc').emit(target, msg);
    } catch (error) {
      console.log(error);
    }
  };
};

客户端

const log = console.log;
const socket = io(host, { transports, timeout: 5 * 1000 });
socket.on('connect', () => {
  const id = socket.id;
  log('#connect:', id);

  socket.on(id, response => {
    log(response);
  });  
});
socket.on('disconnect', () => {}); 
socket.emit('exchange', {
  target: {socketId},
  payload: {
    role,
    type,
    data,
  },
});

我的问题 其实是 不能在服务器主动触发的情况下给客户端发送数据包吗 , 只能被动发送吗 就是客户端发送消息到服务端的时候服务端才能处理 ?不能服务端主动触发吗

@zackCzy 你可以在服务端适当的时机触发,如定时,或者收到 redis 之类的某个事件,或者是 socket 的其他事件

@zackCzy 服务只要用 socket 对象,在适当的时机,emit 事件即可。至于,什么时机,这个可以有很多中设计方案,参考楼上建议。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Azard picture Azard  ·  3Comments

ycvcb123 picture ycvcb123  ·  3Comments

dizhifeng picture dizhifeng  ·  3Comments

Leungkingman picture Leungkingman  ·  3Comments

wujianling picture wujianling  ·  3Comments