WebSocket 使用示例,后台为nodejs

效果图

页面代码

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket Client</title>
  </head>
  <body>
    <script>
      const ws = new WebSocket('ws://localhost:8765')
      ws.onopen = () => {
        console.log('HTML: init!')
        ws.send(`HTML say -> I'm init!`)
      }
      ws.onmessage = event => {
        console.log('HTML listen: ', event.data)
      }
      ws.onerror = error => {
        console.error('HTML Error: ', error)
      }
      ws.onclose = event => {
        if (event.wasClean) {
          console.log(
            'HTML Closed cleanly, code:',
            event.code,
            'reason:',
            event.reason
          )
        } else {
          console.error('HTML Connection died')
        }
      }
    </script>
  </body>
</html>

服务后台代码

javascript 复制代码
const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8765 })

wss.on('connection', ws => {
  console.log('SERVER: init!')
  ws.on('message', message => {
    console.log('SERVER listen: %s', message)
    setInterval(() => {
      function getTwoNum(num) {
        return (+num < 10 ? '0' : '') + num
      }
      const now = new Date()
      const nowStr = `${now.getFullYear()}-${getTwoNum(
        now.getMonth() + 1
      )}-${getTwoNum(now.getDate())} ${getTwoNum(now.getHours())}:${getTwoNum(
        now.getMinutes()
      )}:${getTwoNum(now.getSeconds())}`

      ws.send(`SERVER say -> ${nowStr}`)
    }, 3000)
  })
})

new WebSocket() api说明

var Socket = new WebSocket(url, [protocol] );
参数:

  • url, 指定连接的 URL
  • protocol 是可选的,指定了可接受的子协议

属性:

  • Socket.readyState 只读属性 readyState 表示连接状态(0-表示连接尚未建立; 1-表示连接已建立,可以进行通信; 2-表示连接正在进行关闭; 3-表示连接已经关闭或者连接不能打开)
  • Socket.bufferedAmount 只读属性 bufferedAmount 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数。

事件:

  • open Socket.onopen 连接建立时触发
  • message Socket.onmessage 客户端接收服务端数据时触发
  • error Socket.onerror 通信发生错误时触发
  • close Socket.onclose 连接关闭时触发

方法:

  • Socket.send() 使用连接发送数据
  • Socket.close() 关闭连接
相关推荐
阿蓝灬9 分钟前
React中的stopPropagation和preventDefault
前端·javascript·react.js
天天向上102412 分钟前
vue3 抽取el-dialog子组件
前端·javascript·vue.js
lecepin17 分钟前
AI Coding 资讯 2025-11-05
前端·javascript
excel20 分钟前
Vue 模板解析器 parserOptions 深度解析
前端
前端小咸鱼一条24 分钟前
17.React获取DOM的方式
前端·javascript·react.js
excel26 分钟前
Vue 编译核心中的运行时辅助函数注册机制详解
前端
excel27 分钟前
🌿 深度解析 Vue DOM 编译器模块源码:compile 与 parse 的构建逻辑
前端
excel28 分钟前
深度解析 Vue 编译器中的 transformShow:v-show 指令的编译原理
前端
excel29 分钟前
深度解析:decodeHtmlBrowser —— 浏览器端 HTML 解码函数设计
前端
excel29 分钟前
深度解析:Vue 模板编译器中的 transformVText 实现原理
前端