Socket.IO和HapiJS之间的连接

我们有一个使用HapiJS实现的REST服务器和一个使用Socket.IO实现的Websockets服务器(它们都在单个服务器上运行,但在不同的端口上运行)。 我想通知HapiJS服务器的Websockets服务器发送带有一些数据的事件给特定的客户端。

套接字服务器在端口8081上运行,而REST在8080上。

这个想法是,一个客户做一个行动(POST请求),这是logging在“行动历史”表。 该行为涉及其他用户,因此应在实时发生这种情况时通知他们。 这就是为什么其他用户正在监听websocket连接。

我怎么能告诉套接字服务器发送一个事件到一个特定的客户端,这应该从REST服务器完成?

目前我想了三种方法:

  1. 单独的服务器sockets和rest和使用RabbitMQ沟通
  2. 我试图实现Socket.IO发射器,但它需要Redis数据库(我仍然不知道为什么)。 当我尝试使用发射器从HapiJS路由处理程序连接到套接字时,我得到:

    export function* postRefreshEvent(userId) { var connection = require('socket.io-emitter')({ host: '127.0.0.1', port: 8081 }); connection.in('UserHistory').emit('refresh', userId); return {statusCode: OK} } Error: Ready check failed: Redis connection gone from end event. 

    在RedisClient.on_info_cmd

刷新不在Socket服务器中执行。 我只是看不到日志显示。

  1. 做一个特殊的事件,并使用一个普通的socket.io客户端从hapijs连接到websockets并发出新的事件。

样本GIST 。

你有没有想到这样的事情? 我感谢每一个帮助!

您可以使用普通的旧EventEmitter在socket.io和代码库的hapi部分之间进行通信。 这里有一个例子,说明你如何做到这一点:

 var Hapi = require('hapi'); // Make an event emitter for managing communication // between hapi and socket.io code var EventEmitter = require('events'); var notifier = new EventEmitter(); // Setup API + WS server with hapi 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'); } }); // Setup websocket stuff var io = require('socket.io')(wsServer.listener); io.on('connection', function (socket) { // Subscribe this socket to `action` events 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然后打开你的控制台,你可以用浏览器或cURL(curl http:// localhost:4000 /操作 ),您将看到事件显示在Web控制台中:

在这里输入图像描述

你可以尝试使用https://github.com/hapijs/nes ,通过插件将websockets整合到hapi中。 免责声明我还没有尝试过或使用过的websockets,但似乎融入hapi很好。