浅谈websocket
websocket是一种基于http的通信协议。服务器可以主动向客户端推送信息,客户端也可以像服务器一样发送请求。Websocket允许服务器以全双工方式与客户端通信。特点基于tcp协议,服务器实现起来比较容易。默认端口为80(ws)或443(wss)。握手阶段使用的http协议的数据格式比较轻,性能开销小,通信效率高。可以不受同源限制发送文本或二进制数据,客户端可以像任何服务一样发送信息。协议标识是ws,如果加密的话就是wss,实现客户端和服务端的通信新建一个html文件客户端代码websocket你好websocket
Send开启服务端向客户端发送消息的模式
/body>在html中引入如下js//index.jsconstsendDom=document.getElementById('send');constappDom=document.getElementById('app');constautoDom=document.getElementById('自动发送');constinputContent=document.getElementById('textContent');constsocketPath='ws://192.168.31.40:3000';让定时器=空;让数=0;常量结果=[];//建立连接constws=newWebSocket(socketPath);constsendMyNum=(isSetInterval=false,to='client',val)=>{constsetNum=()=>{num=val||Math.ceil(Math.random()*10);ws.send(JSON.stringify({clientText:`client:hello,我是${num}号`,num,to}));};如果(isSetInterval){timer=setInterval(()=>{setNum();},1000);}else{setNum();}};constrenderHtml=(data)=>{const{serverText,clientText}=JSON.parse(data);appDom.innerHTML='';result.push({serverText,clientText});控制台日志(结果);如果(结果.length>0){让str='';result.forEach((v)=>{str+=`
- ${v.clientText}
- ${v.serverText}
`;});appDom.innerHTML=str;}};//发送数据ws.onopen=function(){console.log('websocketconnectionstart');发送我的号码(假);};//接收服务器发送的消息ws.onmessage=function(evt){console.log(`receive:${evt.data}`);如果(evt.data){renderHtml(evt.data);//接收到数据后关闭定时器clearInterval(timer);//sendMyNum(true)}};//关闭连接ws.onclose=function(){console.log('closed');};//手动发送Client发送消息handleSend.onclick=function(){constval=inputContent.value;if(val===''){alert('请输入您的电话号码');返回;}sendMyNum(false,'client',val);};//自动开始向客户端发送消息autoDom.onclick=function(){sendMyNum(true,'服务器');};新建server目录,新建server代码,主要依赖nodejs-websocket这个库是serverwebsocket代码varws=require("nodejs-websocket");varhttp=require('http');constfs=require('fs');constpath=require('path');constPORT=8080;varserver=http.createServer(function(request,response){response.statusCode=200;response.setHeader('Content-Type','text/html');fs.readFile(path.resolve(__dirname,'../','index.html'),(err,data)=>{if(err!==null){response.end('404');return;}response.end(data);})});server.listen(PORT,function(evt){console.log((newDate())+'服务器正在监听端口8080');});//websocketconsttcp=ws.createServer(function(connection){console.log("新连接")connection.on("text",function(data){const{clientText,num,to}=JSON.parse(data);if(to==='server'){connection.sendText(JSON.stringify({serverText:`server:${num}号,恭喜你,你太幸运了,你已经被清华录取了`,clientText:`${num}号`}));}else{if(num>6){connection.sendText(JSON.stringify({clientText,serverText:`server:${num}号,你很优秀,${num}号,你已经顺利考上北大`,}))}else{connection.sendText(JSON.stringify({serverText:`server:${num}号,非常抱歉,${num}号,你失败了,继续尝试`,clientText,}));};}});connection.sendText(JSON.stringify({serverText:`server:hello,wehaveestablishedaconnection`,clientText:`client:Hello`}))connection.on("close",function(code,reason){console.log("连接关闭");console.log(code,reason);});}).listen(3000);tcp.on('error',(err)=>{console.log(err);})我们可以执行命令nodeserver.js,打开浏览器http://localhost:8080/打开网络,在ws下,可以看到客户端向服务端发送的消息,以及客户端发送的两条消息服务器给客户端一条消息我们可以在请求头中看到一些信息。我们可以在请求头中看到GeneralRequestURL:ws://192.168.31.40:3000/RequestMethod:GETStatusCode:101SwitchingProtocolsRequestHeadersAccept-Encoding:gzip,deflateAccept-Language:zh-CN,zh;q=0.9,en;q=0.8Cache-Control:no-cacheConnection:UpgradeHost:192.168.31.40:3000Origin:http://localhost:8080Pragma:no-cacheSec-WebSocket-Extensions:permessage-deflate;client_max_window_bitsSec-WebSocket-Key:Mk8Au85XqQTn+vuDsfr/kw==Sec-WebSocket-Version:13Upgrade:websocketUser-Agent:Mozilla/5.0(Macintosh;IntelMacOSX10_15_7)AppleWebKit/537.36(KHTML,likeGecko)Chrome/100.0.4896.127/537.36当输入一个号码并向服务器发送消息时,服务器会返回相应的信息。一般来说,服务器会时不时的向前端推送信息,前端会得到推送的信息来展示一系列的页面状态等等。通过上面的例子,我们对websockets的使用有了一个基本的了解。总结websockets其实是需要客户端来处理websockets的。这就是建立连接、断开连接、发送数据、接收数据处理错误这三个步骤。本文更多的websockets可以参考websockets。欢迎关注公众号:网络技术学院努力学习,天天向上!