EventEmitter socket.io hapi . , , :
var Hapi = require('hapi');
var EventEmitter = require('events');
var notifier = new EventEmitter();
var server = new Hapi.Server();
server.register(require('inert'), function () {});
server.connection({ port: 4000, labels: ['api'] });
server.connection({ port: 4001, labels: ['ws'] });
var apiServer = server.select('api');
var wsServer = server.select('ws');
apiServer.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file('index.html');
}
});
apiServer.route({
method: 'GET',
path: '/action',
handler: function (request, reply) {
notifier.emit('action', { time: Date.now() });
reply('ok');
}
});
var io = require('socket.io')(wsServer.listener);
io.on('connection', function (socket) {
notifier.on('action', function (action) {
socket.emit('action', action);
});
});
server.start(function () {
console.log('Server started');
});
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://localhost:4001/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io('http://localhost:4001');
socket.on('action', function (action) {
console.log(action);
});
</script>
</body>
</html>
http://localhost:4000 , http://localhost:4000/action cURL (curl http://localhost:4000/action), , -:
