【管子先生的Node之旅·18】一款基于HTTP协议的百度搜素程序

效果图

search.gif

需求分期

  • 服务端输入搜索内容,服务端实现搜索结果返回客户端
  • 服务端将该搜索结果打印出来

程序实现

服务端
//引入http模块
const http = require('http');
//引入querystring模块
const qs = require('querystring');
//引入cheerio模块
const ci = require('cheerio');
//引入colors模块
require('colors');
//搜索结果
var fruits = [];
//搜索是否完成
var isearch = false;
//创建一个HTTP服务器
const serv = http.createServer((req, res) => {
    let body = '';
    req.on('data', (data) => {
        body += data;
    });
    req.on('end', () => {
        let data = qs.parse(body);
        fruits = [];
        search(data.name, 1);
        setInterval(() => {
            if (isearch) {
                res.writeHead(200);
                res.end('搜索结果\n' + fruits.join(''));
            }
        }, 1000);
    })
});
//启动监听
serv.listen(3000, () => {
    console.log('服务已启动'.yellow);
});

//搜索
function search(val, pn) {
    if (pn < 500) {
        http.request({
            host: 'www.baidu.com',
            path: '/s?' + qs.stringify({ wd: val, pn: pn })
        }, (res) => {
            //接收返回的html
            let html = '';
            res.setEncoding('utf-8');
            res.on('data', (data) => {
                html += data;
            });
            res.on('end', () => {
                $ = ci.load(html);
                let fs = [];
                let s = $('h3.t').each(function(i, elem) {
                    fs.push($(this).text() + '\n');
                });
                fruits.push(fs.join(' '))
                pn += 10;
                search(val, pn);
                fruits = fruits;
            })
        }).end();
    } else {
        isearch = true;
    };
}
客户端
//引入http模块
const http = require('http');
//引入querystring模块
const qs = require('querystring');
//引入colors模块
require('colors');
//往服务器发送消息
function send(theName) {
    //创建一个客户端请求
    http.request({
        host: '127.0.0.1',
        port: 3000,
        url: '/',
        method: 'POST'
    }, (res) => {
        // 获取服务端响应
        let body = '';
        //设置编码
        res.setEncoding('utf-8');
        //接收响应数据
        res.on('data', (data) => {
            body += data;
        });
        //接收完毕回调
        res.on('end', () => {
            console.log(body.blue);
        });
    }).end(qs.stringify({ name: theName }));
}
process.stdout.write('请输入你的搜索内容:'.red);
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (data) => {
    console.log('搜索中...'.red);
    send(data.replace('\r\n', ''));
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,992评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,558评论 25 708
  • 我用着很好 所以也推荐给你。 大家好才是真的好嘛。 今天给大家推荐冬天的暖身暖心小物,冬天太冷,难免的手脚冰凉,泡...
    美丽小狮子阅读 303评论 0 2
  • 三月的海子 鲜花遍野 自九月而来的青草 放下迟疑 春天不需要粉饰 我们围坐在朋友圈 低下头 循着关于你的诗歌和文字...
    杨昊田阅读 545评论 96 71
  • 6cf9a0b2369d阅读 165评论 0 0