WebSocket的优缺点

WebSocket的优缺点

1. WebSocket概念

1.1 WebSocket优点

  1. 低延迟
  2. 全双工
  3. 长期运行
  4. 双向实时通信

1.2 什么是心跳机制

为了保持WebSocket稳定的长连接,在建立连接后,服务器和客户端之间需要通过心跳包来保持连接状态,以防止连接因长时间没有数据传输而被切断.

心跳包是一直特殊的数据包,它不包含任何实际数据,仅用来维持连接状态.

1.3 WebSocket的限制

  1. 不提供加密功能.可以使用ssl或者设置白名单
  2. 不支持老版本的浏览器
  3. 需要对长连接进行维护

2. WebSocket简单代码实现

2.1 服务端

  1. 引入http和websocket模块
  2. 创建http服务器实例
  3. 通过http创建websocket服务器
  4. 当客户端连接到websocket时,触发connection事件
    1. 接收到客户端消息触发message事件,来处理收到的消息,并通过socket.send方法向客户端发送消息.
    2. 当客户端断开连接时,触发close事件.
js 复制代码
const http = require('http');
const WebSocket = require('ws');

const server = http.createServer();
const wss = new WebSocket.Server({ server });
wss.on('connection', (socket)=>{
    console.log('ws连接已经打开!');
    socket.on('message',(message)=>{
        console.log('收到消息'+message);
        socket.send('Hola');
    });
    socket.on('close',()=> {
        console.log('ws连接已关闭');
    });
});

server.on('request',(request,response)=>{
    response.writeHead(200, {'Content-Type':'text/plain'});
    response.end('Hola');
});

server.listen(8800,()=>{
    console.log('服务器已启动,服务端口为8800');
});

2.2 客户端

  1. 创建websocket实例,给它指定服务器地址
  2. 监听websocket事件
    1. 连接打开
    2. 收到消息
    3. 连接关闭
  3. 通过按钮事件发送消息到服务器
html 复制代码
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test-demo</title>
    </head>
    <body>
      <button onclick="sendMsg()">发送消息</button>
    </body>
    <script>
      const socket=new WebSocket("ws://localhost:8800")
      socket.onopen=function(event) {
        console.log("连接建立")
      };
      socket.onmessage=function(event){
        console.log("收到消息:"+event.data)
      };
      socket.onclose=function(event){
        console.log("连接已关闭")
      };
      function sendMsg(){
        socket.send("hello!")
      };
    </script>
</html>

2.3 访问测试

在请求头中带上了Upgrade,服务器也响应成功

当客户端点击"发消息"后,在消息中可以看到客户端发送了Hello.服务器回复了Hola

在console中也能看到服务器返回内容

相关推荐
当下新鲜事2 小时前
车间实测记录:三菱电机MR-J5伺服与压力控制方案的场景适配
网络·物联网·业界资讯
门思科技3 小时前
开源网关有哪些:主流类型梳理
网络·python·物联网
szephyr3 小时前
WebSocket 实战:心跳、断线重连、鉴权,一次讲清
前端·websocket·node.js·长连接·实时通信
llilian_164 小时前
北斗授时卡同步解决方案 gnss授时卡 计算机时间同步板卡
大数据·网络·人工智能·功能测试·51单片机
Vicky_time4 小时前
跨境物流系统架构:美国海外仓与FBA中转海外仓选型技术方案评测
网络·人工智能
玄芯散人4 小时前
【筑基·055】TCP vs UDP:可靠和快速的取舍
网络协议·tcpdump
多多鼠5 小时前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
Allen_LVyingbo7 小时前
三甲医院医疗AI代码库管理系统研究(上)
网络·transformer·知识图谱·健康医疗
迪康coolmu7 小时前
企业文件外发管控落地实践 —— 基于迪康端点安全一体化管理系统
运维·网络·经验分享·安全
小此方7 小时前
Linux网络(十二):HTTP短连接与长连接:从Connection机制到Cookie、Session,彻底理解HTTP的无状态
服务器·网络·http