WebSocket 使用示例,后台为nodejs

本文展示了如何在前端使用WebSocketClient与后端服务器进行实时双向通信,包括HTML页面的连接初始化、消息监听和错误处理,以及服务端的WebSocket服务器设置和数据发送。
摘要由CSDN通过智能技术生成

效果图

在这里插入图片描述

页面代码

<!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>

服务后台代码

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() 关闭连接
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

#老程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值