没有调用'data'事件的回调,为什么?

时间:2014-04-10 15:18:22

标签: node.js

我使用socket来模拟http请求。 这是我的程序

 var request = [
'GET / HTTP/1.1',
'Host: www.baidu.com',
'Connection: keep-alive',
'Cache-Control: no-cache',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Pragma: no-cache',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36',
'Accept-Encoding: gzip,deflate,sdch',
'Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4',
'Cookie: BAIDUID=44BE959D153BFDD6BE362FAE150DF9BF:FG=1; H_PS_TIPFLAG=O; H_PS_TIPCOUNT=1; BD_CK_SAM=1; BDSVRTM=19; H_PS_PSSID=1439_5224_5849_5900_4759_5857_5919'
].join('\r\n');
request += '\r\n';

var net = require('net');

var client = net.connect({
    port: 80,
    host: 'www.baidu.com'
}, function() {
    console.log('client connected');
    client.write(request);
});

client.on('data', function(data) {
    console.log(data.toString());
    client.end();
});

client.on('end', function() {
    console.log('client disconnected');
});

但是没有调用'data'事件的回调,为什么

1 个答案:

答案 0 :(得分:2)

.join最后不会添加额外的\r\n。你需要两个来分隔标题和正文:

request += '\r\n\r\n';