-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (62 loc) · 1.99 KB
/
Copy pathserver.js
File metadata and controls
72 lines (62 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os from 'os';
import Koa from 'koa';
import serve from 'koa-static';
import RedisHelper from './redis-helper';
const REDIS_HOST = 'localhost';
const REDIS_PORT = 6379;
const app = new Koa();
const router = require('koa-router')();
app.use(serve('./public'));
app.use(router.routes());
/**
* Server
*/
const server = app.listen(process.argv[2]);
console.log(`Listening ${process.argv[2]}...`);
const io = require('socket.io').listen(server);
/**
* Redis
*/
const emitter = require('socket.io-emitter')({ host: REDIS_HOST, port: REDIS_PORT });
const redis = require('redis').createClient;
const pub = redis(REDIS_PORT, REDIS_HOST);
const sub = redis(REDIS_PORT, REDIS_HOST);
const redisAdapter = require('socket.io-redis');
io.adapter(redisAdapter({ host: REDIS_HOST, port: REDIS_PORT, pubClient: pub, subClient: sub }));
io.use(middlewareAttachUserId);
const helper = new RedisHelper(redis(REDIS_PORT, REDIS_HOST), os.hostname(), process.argv[2]);
helper.init();
/**
* Events
*/
io.on('connection', (socket) => {
console.log('connection', socket.id, socket.userId);
helper.set(socket.userId, socket.id);
socket.on('disconnect', () => {
console.log('disconnect', socket.id, socket.userId);
helper.del(socket.userId, socket.id);
});
});
/**
* Routing
*/
router.get('/message/to/:id/:message', async (ctx, next) => {
await helper.fetchSocketIds(ctx.params.id)
.then(socketIds => {
console.log('socketIds', socketIds);
ctx.body = `<p>Sent message to socket ids [${socketIds.join(', ')}]</p>`;
socketIds.forEach((socketId) => {
emitter.to(socketId).emit('push_message', `${ctx.params.message} - ${new Date()}`);
});
})
.catch(err => {
console.log(err);
ctx.body = err;
});
});
function middlewareAttachUserId (socket, next) {
// console.log('Token =', socket.handshake.query.token);
// TODO: Using token instead of real userId in this sample.
socket.userId = socket.handshake.query.token;
next(); // MUST call next() in middleware
}