本文主要从实践角度介绍长、短连接在TCP层面的表现,借助Node.JS搭建后台服务,使用WinHTTP、Ajax做客户端请求测试,最后简单涉及WebSocket。
关键字:长连接、短连接、Node.JS、WebSocket.
一两年前,在理论上对长短连接做了学习,那时的技能以客户端为主,所以也止步于客户端和网络抓包,两年来后台技术渐有把握,打算从前到后的实践一遍。如对理论有不理解的,可以先google/百度 一下,或者看看这篇偏理论的介绍:HTTP的长连接和短连接。
1 短连接的表现
/** * * @file 短连接测试服务 * * 启动: node short.js * * @authoer cswuyg * */ var os = require('os'); var http = require('http'); var server = http.createServer(function(req, res) { console.log(req.connection.remoteAddress + ':' + req.connection.remotePort); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); res.destroy(); // destroy immediately }).listen(8124); console.log('start ' + os.hostname() + ':8124');
在浏览器访问:http://hostname:8124
使用WireShark抓包:
2 长连接的表现
/** * * @file 长连接测试服务器 * * 启动: node persistent.js * * ./a.html 为同目录下的ajax请求测试文件 * * @authoer cswuyg * */ var os = require('os'); var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res) { if (/^\/a.html/.test(req.url)) { fs.createReadStream('a.html').pipe(res); } else { console.log(req.connection.remoteAddress + ':' + req.connection.remotePort); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); } }).listen(8124); server.setTimeout(0); //设置不超时,所以服务端不会主动关闭连接 console.log('start ' + os.hostname() + ':8124');
xx: const wchar_t* lpszAcceptedType[] = {L"*/*", NULL}; request_handle_ = ::WinHttpOpenRequest(connect_handle, L"GET", url_path_.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, lpszAcceptedType, 0); if (request_handle_ == NULL) { return FALSE; } DWORD time_out = 5000; ::WinHttpSetOption(request_handle_, WINHTTP_OPTION_CONNECT_TIMEOUT, &time_out, sizeof(DWORD)); ::WinHttpSendRequest(request_handle_, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); ::WinHttpReceiveResponse(request_handle_, NULL); Recv(); goto xx; //测试代码,不惧goto~
<script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> <script> function callNode() { $.ajax({ cache : false, url : 'http://xxxxxyouhost:8124', data : {}, success : function(response, code, xhr) { console.log(response); console.log(code); callNode(); } }); }; callNode(); </script>
3、WebSocket