当前位置: 首页 > 后端技术 > Node.js

WebSocket简介

时间:2023-04-03 16:20:01 Node.js

*{填充:0;margin:0;}.fl{float:left;}.fr{float:right;}li::before{content:".";显示:块;高度:0;明确:两者;ility:hidden;}.wrap{position:relative;宽度:380px;保证金:自动;高度:600px;背景色:#eee;padding:10px;}.wrapul{overflow:auto;height:550px;}li{list-style:none;margin:2px;}li:nth-child(even)p{background-color:rgb(86,107,177);}lip{font-size:20px;font-family:"MicrosoftYahei",serif,Arial,Helvetica,sans-serif;边界半径:6px;填充:4px;边距:2px4px;空白:换行;text-align:left;}lip.fr{background-color:rgb(61,185,30);}.send-cont{position:absolute;底部:10px;z-指数:999;宽度:98%;保证金:自动;}.发送连续输入{显示:内联块;大纲:无;边框:2px实心#080;边界半径:6px;行高:30px;字体大小:16px;text-align:left;}.send-continput:first-child{width:70%;}.send-continput[type="button"]{width:20%;背景色:#080;颜色:#fff;文本对齐:居中;填充:1px;}WebSocket是HTML5开始提供的一种在单TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换更加容易,允许服务器主动向客户端推送数据。在WebSocketAPI中,浏览器和服务器只需要完成一次握手,两者之间就可以直接建立持久连接,进行双向数据传输。现在,很多网站都使用Ajax轮询来实现推送技术。轮询是在特定的时间间隔(比如每隔1秒),浏览器向服务器发送一个HTTP请求,然后服务器将最新的数据返回给客户端的浏览器。这种传统模式带来的弊端很明显,就是浏览器需要不断向服务器发送请求,但是HTTP请求可能包含很长的header,真正有效的数据可能只有一小部分,显然是浪费了很多带宽和其他资源。HTML5定义的WebSocket协议可以更好的节省服务器资源和带宽,实现更实时的通信。浏览器通过JavaScript向服务器发送建立WebSocket连接的请求。连接建立后,客户端和服务端可以直接通过TCP连接进行数据交换。获取WebSocket连接后,可以使用send()方法向服务器发送数据,使用onmessage事件接收服务器返回的数据。DEMO如下//clientsidefileletsocket=newWebSocket('ws://localhost:9999');//连接成功时执行回调函数socket.onopen=function(){console.log('客户端连接成功');//向服务器发送消息socket.send('这是客户端发送给服务器的消息');}//通过添加属性绑定事件socket.onmessage=function(res){console.log('从服务器收到的响应是',res);}//serversidefile/*npmiws-S*//*用ws模块启动一个websocket服务器,监听9999端口*/letWebSocketServer=require('ws').服务器;letwsServer=newWebSocketServer({port:9999});wsServer.on('connection',socket=>{console.log('服务器连接成功');socket.on('message',msg=>{console.log('从客户端收到的消息是'+msg);socket.send('这是服务端发给客服的消息');})})简单模拟智能客服聊天*{填充:0;margin:0;}.fl{float:left;}.fr{float:right;}li::before{content:".";显示:块;高度:0;明确:两者;ility:hidden;}.wrap{position:relative;宽度:380px;保证金:自动;高度:600px;背景色:#eee;padding:10px;}.wrapul{overflow:auto;height:550px;}li{list-style:none;margin:2px;}li:nth-child(even)p{background-color:rgb(86,107,177);}lip{font-size:20px;font-family:"MicrosoftYahei",serif,Arial,Helvetica,sans-serif;边界半径:6px;填充:4px;边距:2px4px;空白:换行;text-align:left;}lip.fr{background-color:rgb(61,185,30);}.send-cont{position:absolute;底部:10px;z-指数:999;宽度:98%;保证金:自动;}.发送连续输入{显示:内联块;大纲:无;边框:2px实心#080;边界半径:6px;行高:30px;字体大小:16px;text-align:left;}.send-continput:first-child{width:70%;}.send-continput[type="button"]{width:20%;背景色:#080;颜色:#fff;文本对齐:居中;填充:1px;}constcontents=['你好','嗨','你好','很高兴认识你','你好吗','你好吗']letWebSocketServer=require('ws').Server;letwsServer=newWebSocketServer({port:9999});wsServer.on('connection',socket=>{console.log('服务器连接成功');socket.on('message',msg=>{console.log('from客户端收到的信息是'+msg);socket.send(contents[parseInt(Math.random()*contents.length)]);})})