用node.js套接字客户端发送事件到sails.js(0.11.x)

服务器 :sails.js(0.11.x)是服务器

客户端 :一个包含sails.io@0.11.5和socket.io-client@1.3.5的node.js脚本

大图 :我有或将有一个连接到sails.js服务器的nod​​e.js脚本的场,并将执行各种任务。

即时目标 :我想在客户端 – >服务器的套接字连接期间发出事件,例如:

socket.emit('got_job', job.id); 

为什么? 如果可能的话,我可以在一个控制器(或控制器+服务)中的服务器端创build各种事件处理程序,并保持我的代码清洁,同时pipe理客户端/服务器端点之间的一组有状态事务以支持此脚本场。

文档 :这是如何使用socket.io客户端sails.js这个每帆的文档: https : //github.com/balderdashy/sails.io.js? files =1# for-nodejs

我没有太多的代码来分享除了那个链接之外的东西,但是我会在这里粘贴它,以防万一:

 var socketIOClient = require('socket.io-client'); var sailsIOClient = require('sails.io.js'); // Instantiate the socket client (`io`) // (for now, you must explicitly pass in the socket.io client when using this library from Node.js) var io = sailsIOClient(socketIOClient); // Set some options: // (you have to specify the host and port of the Sails backend when using this library from Node.js) io.sails.url = 'http://localhost:1337'; // ... // Send a GET request to `http://localhost:1337/hello`: io.socket.get('/hello', function serverResponded (body, JWR) { // body === JWR.body console.log('Sails responded with: ', body); console.log('with headers: ', JWR.headers); console.log('and with status code: ', JWR.statusCode); // When you are finished with `io.socket`, or any other sockets you connect manually, // you should make sure and disconnect them, eg: io.socket.disconnect(); // (note that there is no callback argument to the `.disconnect` method) }); 

我研究过的东西 :我已经钻进了这些对象的各个层面,我似乎无法find任何暴露的东西。 而只是试图io.socket.emit(),因为它不存在。 但是io.socket.get()和io.socket.post()等工作正常。

 console.log(socketIOClient); console.log(sailsIOClient); console.log(io); console.log(io.socket._raw); console.log(io.sails); 

谢谢,我会尽力根据需要进行更新以进行澄清。

更新

杂项服务器信息。

  • 我正在端口443上使用nginx,并使用SSL终止,指向分开的端口(3000-3003)上的4(以及更多)sails.js实例。
  • 我还使用Redis进行会话和套接字。

你近了:

你的io.socket.get调用就像一个restAPI调用。 你需要一个sails控制器绑定到url'/ hello'上的获取请求,

 //client io.socket.get('/hello', function serverResponded (body, JWR) { //this is the response from the server, not a socket event handler console.dir(body);//{message:"hello"} }); 

 config/routes.js: { 'get /hello':'MyController.hello' } //controllers/MyController { hello:function(req,res){ res.json({message:"hello"}); } } 

你正在寻找的方法是,io.socket.on('eventName');

这是一个例子:

 //client io.socket.get('/hello', function serverResponded (body, JWR) { //all we're doing now is subscribing to a room console.dir(body); }); io.socket.on('anevent',function(message){ console.dir(message); }); in config/routes.js: { 'get /hello':'MyController.hello' } //controllers/MyController { hello:function(req,res){ sails.sockets.join(req.socket,'myroom'); res.json({message:'youve subscribed to a room'}); } } 

我们已经有效地完成了,将套接字设置为“空间”的一部分,这个空间基本上是一个事件名称空间。 然后,其他一些控制器只需要这样做:

 sails.sockets.broadcast('myroom','anevent',{message:'socket event!'}); 

在这个调用之后,你会收到io.socket.on('anevent')的callback消息。