我正在使用带套接字 io 的sailsjs。帆的版本是 0.10.5。我有以下套接字客户端进行测试:
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('/join', 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, e.g.:
//io.socket.disconnect();
// (note that there is no callback argument to the `.disconnect` method)
});
io.socket.on('myroom', function(response){
console.log(response);
});
在我的 config/routes.js 中,我有以下内容:
'get /join':'LayoutController.join'
在我的 api/controller/LayoutController 中,我有以下内容:
module.exports={
join: function(req, res) {
console.log('Inside Join');
sails.sockets.join(req.socket,'myroom');
res.json({message:'youve subscribed to a room'});
}
};
我遇到的问题是 Controller 内的 join 函数永远不会通过套接字调用 io.socket.get('/join',...) 被触发。 Controller 中的 console.log 永远不会打印,也不会响应客户端。如果我通过 http 做同样的测试,它会触发 join 功能。我第一次使用套接字。谁能建议我在这里做错了什么?
最佳答案
您可以在套接字与服务器建立连接后尝试运行 get 请求,因为它将通过套接字充当对 Sails 服务器的虚拟请求。您可以将代码更改为以下内容:
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.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.on('connect', function(){
io.socket.get('/join', 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, e.g.:
//io.socket.disconnect();
// (note that there is no callback argument to the `.disconnect` method)
});
});
io.socket.on('myroom', function(response){
console.log(response);
});
这只会在套接字连接后调用路由。希望这可以帮助!
关于socket.io - 在sails js socket.io中使用io.socket.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33074428/