我有一个场景需要构建一个Web套接字客户端。客户端需要首先通过HTTP代理发出CONNECT请求。连接后,我手动在套接字上写入以升级连接。在Wireshark中,我看到服务器响应成功升级了连接,但我的req.on('upgrade')
事件从未触发!我已经看过conn
套接字回到req
,但我无法让它工作。
有什么想法吗?
var http = require('http');
// make a request
var options = {
port:8080,
host:'http.proxy.com',
path: 'echo.websocket.org:80',
headers: {
'Host': 'echo.websocket.org',
'Proxy-Connection':'keep-alive'
},
method: 'CONNECT'
};
var req = http.request(options);
req.end();
req.on('connect', function(res, conn, connectHead) {
console.log('connected');
// manually request Web Socket upgrade
conn.write('GET /?encoding=text HTTP/1.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nHost: echo.websocket.org\r\nOrigin: http://www.websocket.org\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36\r\n\r\n');
});
// this event never fires!
req.on('upgrade', function (res, socket, upgradeHead) {
console.log('got upgraded!');
socket.write('test');
socket.on('data', function (data) {
console.log('req on data');
console.log(data);
});
});