websocket聊天室示例

服务端代码

const ws = require('nodejs-websocket')
console.log('开始建立连接...')

const session = {}
const log = []

const server = ws.createServer((conn) => {
  conn.on('text', (str) => {
    console.log('message: ' + str)

    const data = JSON.parse(str)
    const {type, nickname, message} = data
    if (type === 'open') {
      session[conn.key] = conn

      conn.sendText(JSON.stringify({data: log}))
    }
    if (type === 'send') {
      log.push(data)

      Object.values(session).map(m => {
        m.sendText(JSON.stringify({data: [data]}))
      })
    }
  })

  conn.on('close', (code, reason) => {
    console.log('关闭连接')

    delete session[conn.key]
  })

  conn.on('error', (code, reason) => {
    console.log('异常关闭')
  })
}).listen(8090)

console.log('websocket建立完毕')

客户端代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>聊天室</title>
  </head>
  <body>
    <div>昵称 <input type="text" id="nickname" /></div>
    <div>内容 <input type="text" id="msg" /></div>
    <button id="send">发送</button>
    <ul id="msgList"></ul>

    <script>
      const selector = (name) => document.querySelector(name)
      const ws = new WebSocket('ws://localhost:8090')

      ws.onopen = (e) => {
        console.log('连接服务器成功')
        const str = JSON.stringify({
          type: 'open'
        })
        ws.send(str)
      }

      ws.onclose = (e) => {
        console.log('服务器关闭')
      }

      ws.onerror = (e) => {
        console.log('连接出错')
      }

      // 接受服务器的消息
      ws.onmessage = (e) => {
        const res = JSON.parse(e.data)
        console.log(res)
        
        res.data.map(m => appendLog(m))
      }

      function appendLog ({nickname, message}) {
        const msgList = selector('#msgList')
        const msgElme = document.createElement('li')
        msgElme.innerHTML = `${nickname}: ${message}`
        msgList.appendChild(msgElme)
      }
      
      // 发送消息
      selector('#send').onclick = sendMsg
      selector('#msg').onkeydown = (event) => {
        if (event.keyCode === 13) {
          sendMsg()
        }
      }
      function sendMsg () {
        const nickname = selector('#nickname').value.trimStart().trimEnd()
        if (!nickname) {
          alert('请输入昵称')
          return
        }
        const message = selector('#msg').value
        if (ws.readyState === WebSocket.OPEN) {
          const str = JSON.stringify({
            nickname,
            message,
            type: 'send'
          })
          ws.send(str)
        }
      }
    </script>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值