我使用socket.io运行了一个websocket服务器:
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);
这个服务器可以使用简单的socket-io客户端工作:
var socket = require('socket.io-client')('http://127.0.0.1:1337');
socket.on('connect', function(){});
socket.on('time', function(data){console.log(data);});
socket.on('disconnect', function(){});
我尝试使用cURL发送连接请求,但失败了:
curl --verbose -i -N -H "Upgrade: websocket" -H "Connection: Upgrade" -H "Host: 127.0.0.1" -H "Origin: http://127.0.0.1" http://127.0.0.1:3000/
* Connected to 127.0.0.1 (127.0.0.1) port 3000 (#0)
> GET /socket.io HTTP/1.1
> User-Agent: curl/7.37.1
> Accept: */*
> Upgrade: websocket
> Connection: Upgrade
> Host: 127.0.0.1
> Origin: http://127.0.0.1
>
* Empty reply from server
* Connection #0 to host 127.0.0.1 left intact
curl: (52) Empty reply from server
如果我删除了"升级:websocket",那么服务器将发回html页面。 "升级:websocket"应该告诉服务器将HTTP连接升级到websocket连接。为什么它没有用?