前端开发攻略---webSocket的简单实现与使用

1、演示

2、实现流程

安装依赖

npm i ws

服务端代码

const WebSocket = require('ws')

// 创建一个 WebSocket 服务器,监听端口 3000
const wss = new WebSocket.Server({ port: 3000 })

// 监听连接事件
wss.on('connection', function connection(ws) {
  console.log('客户端已连接')

  // 监听客户端发送的消息
  ws.on('message', function incoming(message) {
    console.log('收到消息', message.toString())
    // 原样将消息发送回客户端
    ws.send(message.toString())
  })

  // 监听连接关闭事件
  ws.on('close', function () {
    console.log('客户端断开连接')
  })
})

客户端代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket Demo</title>
  </head>
  <body>
    <h1>WebSocket Demo</h1>
    <input type="text" id="messageInput" placeholder="发送消息" />
    <button onclick="sendMessage()">发送</button>
    <ul id="messages"></ul>

    <script>
      const socket = new WebSocket('ws://localhost:3000')

      // 监听连接打开事件
      socket.addEventListener('open', function (event) {
        console.log('服务端已连接')
      })

      // 监听接收消息事件
      socket.addEventListener('message', function (event) {
        console.log('收到信息', event.data)
        displayMessage(event.data)
      })

      // 将消息显示在页面上
      function displayMessage(message) {
        const messages = document.getElementById('messages')
        const li = document.createElement('li')
        li.textContent = message
        messages.appendChild(li)
      }

      // 发送消息到服务器
      function sendMessage() {
        const input = document.getElementById('messageInput')
        const message = input.value
        socket.send(message)
        input.value = ''
      }
    </script>
  </body>
</html>

 

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 18:24:01       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 18:24:01       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 18:24:01       57 阅读
  4. Python语言-面向对象

    2024-07-09 18:24:01       68 阅读

热门阅读

  1. 面试题 14- I. 剪绳子

    2024-07-09 18:24:01       33 阅读
  2. 机器学习 - 比较检验

    2024-07-09 18:24:01       28 阅读
  3. Mac OS系统中Beyond Compare 4破解方式

    2024-07-09 18:24:01       25 阅读
  4. Mongodb索引的创建与命名

    2024-07-09 18:24:01       27 阅读
  5. 搭建纯净的SpringBoot工程

    2024-07-09 18:24:01       25 阅读
  6. 新型开发语言的试用感受-仓颉语言发布之际

    2024-07-09 18:24:01       35 阅读
  7. ubuntu 如何解压tar

    2024-07-09 18:24:01       20 阅读
  8. VScode 常用插件

    2024-07-09 18:24:01       29 阅读