我正在使用带套接字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'});
}
};
我遇到的问题是控制器内的join函数永远不会通过套接字调用io.socket.get('/ join',...)触发。控制器中的console.log从不打印,也没有响应客户端。如果我通过http进行相同的测试,它会触发join功能。我是第一次使用socket。任何人都可以在这里建议我做错了吗?
答案 0 :(得分:0)
您可以在套接字与服务器建立连接后尝试运行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);
});
这将仅在套接字连接后调用路由。希望这有帮助!