只要动手做起来,多投入时间和精力、耐心去研究,以大多人的智商加google,平时遇到的大部分问题我们都是可以自己解决的,大部分的知识我们都是可以掌握的。
我们都知道http协议是单向请求的,无法实现双向通信,它只能从客户端发送请求,然后服务端再响应请求,无法做到服务端主动向客户端去推送消息。
尽管可以通过setTimeout/setInterval轮询的方式来不断去刷新获取服务端的数据,但是轮询的效率低,非常浪费资源。webscoket就是为了解决这一问题而存在的。
webscoket的特点:
1、建立在Tcp协议之上
2、与http协议有着很好的兼容性
3、通信高效,因为它的数据格式比较轻量、性能开销小
4、可以发送文本和二进制数据
5、没有同源限制
6、协议标识符是ws
简单的通信原理如下
客户端的实现:
浏览器端的实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>WebSocket</title> </head> <body> <h1>Echo Test</h1> <input id="sendTxt" type="text"/> <button id="sendBtn">发送</button> <div id="recv"></div> <script type="text/javascript"> var WebSocket = new WebSocket("ws://localhost:8080"); WebSocket.onopen = function(){ console.log('websocket open'); document.getElementById("recv").innerHTML = "Connected"; } WebSocket.onclose = function(){ console.log('websocket close'); } WebSocket.onmessage = function(e){ console.log(e.data); document.getElementById("recv").innerHTML = e.data; } document.getElementById("sendBtn").onclick = function(){ var txt = document.getElementById("sendTxt").value; WebSocket.send(txt); } </script> </body> </html>
服务端实现:
nodejs搭建服务器,可以参考git上的《一起学nodejs》搭建服务器
文件目录下 npm install webscoket
var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } var connection = request.accept('', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); });
参考资料:
客户端(浏览器端)实现参考阮一峰:http://www.ruanyifeng.com/blog/2017/05/websocket.html