我有一个根据示例here配置的resitfy服务器和socketio服务器。 我的要求是从处理程序中引发socket.io事件。所以,我的代码看起来像这样:
var restify = require('restify');
var socketio = require('socket.io');
var server = restify.createServer();
server.get('/', function (req, res, next) {
res.json(204, null);
io.emit("sample", {"sample":"event"});
next();
});
server.listen(8080, function () {
console.log('socket.io server listening at %s', server.url);
});
我的客户端代码非常简单,如下所示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
</head>
<body>
<script src="socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
socket.on('sample', function (data) {
console.dir(data);
});
</script>
</body>
</html>
当我启动服务器时,服务器在客户端第一次连接后就存在了,这在日志中找到了:
socket.io:server initializing namespace / +0ms
socket.io:server creating engine.io instance with opts {"path":"/socket.io"} +3ms
socket.io:server attaching client serving req handler +1ms
socket.io server listening at http://0.0.0.0:8080
socket.io:server incoming connection with id U9hLZRlbsGfvI8QPAAAA +2s
socket.io:client connecting to namespace / +4ms
socket.io:namespace adding socket to nsp / +0ms
http.js:690
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
at ServerResponse.format (/home/vagrant/socket.io-server-example/node_modules/restify/lib/response.js:109:10)
at ServerResponse.send (/home/vagrant/socket.io-server-example/node_modules/restify/lib/response.js:231:24)
at emitRouteError (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:152:13)
at onRoute (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:610:21)
at Router.find (/home/vagrant/socket.io-server-example/node_modules/restify/lib/router.js:512:5)
at Server._route (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:604:21)
at routeAndRun (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:572:14)
at Server._handle (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:592:9)
at Server.onRequest (/home/vagrant/socket.io-server-example/node_modules/restify/lib/server.js:255:14)
我无法理解的是,如何使用restify从同一端口提供REST API和socket.io事件? 为什么restify会抱怨一旦发送标题就无法设置标题?
我错过了一些基本的东西吗?
答案 0 :(得分:2)
尝试使用此示例
将listen
方法的结果传递给socketio,然后使用io
实例在处理程序上发送这些事件。
var restify = require('restify');
var server = restify.createServer();
var app = server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
var io = require("socket.io")(app);
function respond(req, res, next) {
res.send('hello ' + req.params.name);
io.emit('sample',{"data":"hello from server."});
next();
}
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);
io.on('connection', function(socket){
console.log('new connection');
});