1 const http = require('http'); 2 const querystring = require("querystring"); 3 var postData = querystring.stringify({ 4 'msg': 'Hello World!' 5 }); 6 // Create an HTTP server 7 var srv = http.createServer((req, res) => { 8 res.writeHead(200, {'Content-Type': 'text/plain'}); 9 res.end('okay'); 10 }); 11 srv.on('upgrade', (req, socket, head) => { 12 13 socket.write('HTTP/1.1 101 Web Socket Protocol Handshake ' + 14 'Upgrade: WebSocket ' + 15 'Connection: Upgrade ' + 16 ' '); 17 18 socket.on("data", (d)=> { 19 console.log(d.toString()) 20 }); 21 socket.on("end", ()=> { 22 socket.write("发送服务器的消息"); 23 socket.end(); 24 if (!socket.destroyed) { 25 console.log(" socket.end 会销毁socket,不信你可以执行end,看会不会进入这个方法") 26 if (socket.destroy) { 27 socket.destroy(); 28 console.log(!socket.destroyed) 29 } 30 31 } 32 }); 33 }); 34 35 // now that server is running 36 srv.listen(1337, '127.0.0.1', () => { 37 38 // make a request 39 var options = { 40 port: 1337, 41 hostname: '127.0.0.1', 42 headers: { 43 'Connection': 'Upgrade', 44 'Upgrade': 'websocket' 45 } 46 }; 47 48 var req = http.request(options); 49 req.on('upgrade', (res, socket, upgradeHead) => { 50 socket.write('发送客户端的消息 '); 51 socket.end(); 52 53 socket.on('data', (chunk) => { 54 console.log(chunk.toString()); 55 }); 56 socket.on('end', () => { 57 console.log("服务器消息接收完毕"); 58 console.log("socket已经被销毁",socket.destroyed) 59 }); 60 61 }); 62 63 req.end(); 64 65 66 });
整个流程是
1 :request的 header里加上:
'Connection': 'Upgrade',
'Upgrade': 'websocket'
生成的http.ClientRequest 最后一定要调用end函数,不然服务器会一直等待你消息发送完毕
2: 服务器监听 ‘Upgrade’,然后返回:
'HTTP/1.1 101 Web Socket Protocol Handshake ' + 'Upgrade: WebSocket ' + 'Connection: Upgrade ' + ' '
维基百科里说了,这样叫作握手!
这样的话,Upgrade 就算建立起来了。
3:然后就可以通过socket相互消息了。记住socket.end一旦执行,就会断开这次的tcp链接了。