我正在尝试将字符串写入套接字(套接字称为“响应”)。这是我到目前为止的代码(我正在尝试实现字节缓存代理......):
var http = require('http');
var sys=require('sys');
var localHash={};
http.createServer(function(request, response) {
var proxy = http.createClient(80, request.headers['host'])
var proxy_request = proxy.request(request.method, request.url, request.headers);
proxy_request.addListener('response', function (proxy_response) {
proxy_response.addListener('data', function(x) {
var responseData=x.toString();
var f=50;
var toTransmit="";
var p=0;
var N=responseData.length;
if(N>f){
p=Math.floor(N/f);
var hash="";
var chunk="";
for(var i=0;i<p;i++){
chunk=responseData.substr(f*i,f);
hash=DJBHash(chunk);
if(localHash[hash]==undefined){
localHash[hash]=chunk;
toTransmit=toTransmit+chunk;
}else{
sys.puts("***hit"+chunk);
toTransmit=toTransmit+chunk;//"***EOH"+hash;
}
}
//remainder:
chunk=responseData.substr(f*p);
hash=DJBHash(chunk);
if(localHash[hash]==undefined){
localHash[hash]=chunk;
toTransmit=toTransmit+chunk;
}else{
toTransmit=toTransmit+chunk;//"***EOH"+hash;
}
}else{
toTransmit=responseData;
}
response.write(new Buffer(toTransmit)); /*error occurs here */
});
proxy_response.addListener('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.addListener('data', function(chunk) {
sys.puts(chunk);
proxy_request.write(chunk, 'binary');
});
request.addListener('end', function() {
proxy_request.end();
});
}).listen(8080);
function DJBHash(str) {
var hash = 5381;
for(var i = 0; i < str.length; i++) {
hash = (((hash << 5) + hash) + str.charCodeAt(i)) & 0xffffffff;
}
if(hash<-1){
hash=hash*-1;
}
return hash;
}
问题是,我在 Firefox 中不断收到“内容编码错误”。就好像 gizipped 的内容没有被正确传输。我已通过 console.log(x) 和 console.log(toTransmit) 确保“toTransmit”与“x”相同。
值得注意的是,如果我将 response.write(new Buffer(toTransmit))
替换为 response.write(x)
,代理会按预期工作,但是我需要做一些有效载荷分析,然后传递“toTransmit”,而不是“x”。
我也尝试过 response.write(toTransmit)
(即没有转换为缓冲区)并且我不断收到相同的内容编码错误。
我真的被困住了。我以为我已经通过根据另一个线程(http://stackoverflow.com/questions/7090510/nodejs-content-encoding-error)将字符串转换为缓冲区来解决这个问题,但我重新打开了一个新线程讨论我遇到的这个新问题。
我应该补充一点,如果我通过 Opera 中的代理打开一个页面,我会得到 gobblydeegook - 就好像 gzip 压缩的数据被损坏了一样。
非常感谢任何见解。
非常感谢,
最佳答案
关于javascript - Node : convert string to buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7094615/