NMP*_*NMP 4 sockets rest node.js hapijs socket.io-1.0
我们有一个用HapiJS实现的REST服务器和一个用Socket.IO实现的Websockets服务器(它们都在单个服务器上但在不同的端口上运行).我想从HapiJS服务器通知Websockets服务器,将包含一些数据的事件发送到特定客户端.
套接字服务器在端口8081上运行,REST在8080上运行.
这个想法是客户端发出一个操作(POST请求),该操作记录在"操作历史记录"表中.该操作涉及其他用户,因此应在实时发生时通知他们.这就是其他用户正在监听websocket连接的原因.
如何告诉套接字服务器向特定客户端发出事件,应该从REST服务器完成?
我现在想了3种方法:
我试图实现Socket.IO-Emitter,但它需要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.
Run Code Online (Sandbox Code Playgroud)
在RedisClient.on_info_cmd
刷新未在套接字服务器中执行.我只是看不到日志显示.
一个示例GIST.
你有没有想到这样的事情?我感谢每一个帮助!
Mat*_*son 10
您可以使用普通的旧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');
});
Run Code Online (Sandbox Code Playgroud)
这是客户端的基本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>
Run Code Online (Sandbox Code Playgroud)
如果您运行此操作并浏览http://localhost:4000并打开控制台,则可以http://localhost:4000/action使用浏览器或cURL(curl http:// localhost:4000/action)发出请求,您将看到事件显示在Web控制台中: