我试图在socket.io上使用hapijs,并且已经搜索了很多关于如何以正确的方式将socket.io集成到hapi服务器中。我发现,有一种方法就是example,而我仍然不确定这是否可行。我不得不承认我是新手,我还在学习它:)
var Path = require('path');
var Hapi = require('hapi');
var socketio = require('socket.io');
var server = new Hapi.Server();
server.connection({port: 3000});
server.register(require('vision'), function (err) {
server.views({
engines: {
ejs: require('ejs')
},
relativeTo: __dirname,
path: 'templates'
});
});
var plugins = [
{register: require('./lib/index.js')}
];
server.register(plugins, function (err) {
server.start(function () {
io = socketio.listen(server.listener);
io.on('connection', function (socket) {
socket.on('create', function (room) {
socket.join(room);
console.log("Joined room: " + room);
socket.emit('message', "Joined room");
});
});
console.log('Server running at:', server.info.uri);
});
});
lib / index.js
exports.register = function(server, options, next) {
var tasks = [];
server.route([
{
method: 'GET',
path: '/tasks',
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
{
method: 'POST',
path: '/tasks/{name}',
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
{
method: 'POST',
path: '/tasks',
handler: function (request, reply) {
io.emit('message', "Test");
}
}
]);
next();
}
exports.register.attributes = {
name: 'routes-tasks',
version: '1.0.0'
};
如果这不是使用hapijs的方式,请纠正我。
答案 0 :(得分:0)
socket.disconnect('unauthorized'); or socket.close();
2)为每个订阅使用auth
{
method: 'POST',
path: '/tasks/{name}',
auth: auth,
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
3)重要的是使用Access-Control-Allow-Origin否则会发生websocket劫持。
request.response.header('Access-Control-Allow-Origin', 'your domain')
如果您需要进一步的信息,请告诉我。我很乐意帮助