我正在尝试使用以下代码(从this gist中提取):
var io = require('socket.io-client');
var request = require('request');
var xhr = require('socket.io-client/node_modules/xmlhttprequest');
var xhrOriginal = require('xmlhttprequest');
var myUrl = 'http://192.168.56.101:1337';
var cookieJar = request.jar();
// From socket.io-client's module 'xmlhttprequest', rewrie its XMLHttpRequest function.
xhr.XMLHttpRequest = function() {
this.XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(this, arguments);
this.setDisableHeaderCheck(true); // Allow header modifications.
// Rewrite the 'open' function.
var openOriginal = this.open;
this.open = function(method, url, async, user, password) {
openOriginal.apply(this, arguments);
var header = cookieJar.get({url: myUrl}).map(function(cookie) {
return cookie.name + '=' + cookie.value;
}).join('; ');
this.setRequestHeader('cookie', header);
};
};
// Send the cookie first before attempting to connect via socket-io,
// thus, avoiding the handshake error.
request.post({jar: cookieJar, url: myUrl}, function(err, resp, body) {
var socket = io.connect(myUrl);
socket.on('connecting', function() {
console.log('(II) Connecting to server');
});
socket.on('connect', function() {
console.log('(II) Successfully connected to server');
});
socket.on('error', function(reason) {
console.log('(EE) Error connecting to server: ' + reason);
});
socket.on('disconnect', function(reason) {
console.log('(II) Disconnected from server\n');
});
});
使用socket.io/sails.js实现更简单的握手过程,但我无法使其工作。
有人可以解释如何正确使用它吗?是否打算以某种方式在客户端中以导入的脚本运行?或作为服务页面?
提前致谢。