I am new in socket.io, and I am trying to push specific data to different client-end base on their information in database. I did a very simple practice with socket.io:
```
//app.js
const Koa = require(‘koa');
const router = require('koa-router')();
const server = require('koa-static');
const app = new Koa();
const http = require('http').createServer(app.callback());
const io = require('socket.io')(http);
app.use(server(__dirname + '/'));
app.use(require('./controller')());
io.on('connection', (socket) => {
//each client just take its specific information
socket.on('messge', (msg) => {
io.to(socket.id).emit('message', socket.id);
});
})
app.io = io; //trying to let controller use 'io' by 'app.io'
http.listen(9000);
```
The code above works well, at least those clients side just get their socket.id and do not emit to others. But all the main data handlings are in controller, so I use app.io=io to pass socket.io to controllers. When I use io in controller:
```
//a_controller.js
let fnTestSocketIO = async(ctx, next) => {
let socketIO = ctx.app.io;
//just use like in the app.js, but process doesn't go in this part
socketIO.on('message', (socket) => {
console.log('id', socket.id);
});
ctx.response.body = "response from 'test socket.io'";
}
...
module.exports = {
"GET /test/socket-io": fnTestSocketIO,
}
``` Unfortunately, socketIO.on(...) does not work.
Expected behaviour
- yarn start
ioinapp.jscan emit message if the client emitmessage.- But no things show from the
iowhen I send request in the api/test/socket-io. (It can response, but not go thorughsocketIO.on(...))
Setup
- OS: Ubuntu 14.04
- browser: Google Chrome 58
- socket.io version: 1.7.3
Other information (e.g. stacktraces, related issues, suggestions how to fix)
I can use:
```
//a_controller.js
let fnTestSocketIO = async(ctx, next) => {
let socketIO = ctx.app.io;
socketIO.emit('message', 'something');
ctx.response.body = "response from 'test socket.io'";
}
```
to emit, but it will send data to all clients. I think I need socket ids to send data, so I tried:
```
//a_controller.js
let sid = null;
for(let id in socketIO.sockets.sockets) {
sid = id;
}
```
to get socket's id, however, it is a bad practice obviously.
Are there any hits for this? Thank you so much.
via Tony
No comments:
Post a Comment