WEBSOCKET

106 阅读1分钟

websocket

  1. open
  2. close
  3. error
  4. message
  5. connection

前端

  1. open
  2. close
  3. error
  4. message
<!-- entry.html -->
<!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="username">
    <button id="btn">点击进入聊天室</button>
  </div>

  <script src="./js/entry.js"></script>
</body>

</html>
<!-- index.html -->
<!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>Document</title>
</head>

<body>
  <input type="text" id="message">
  <button id="sendBtn">发送消息</button>
  <div id="list"></div>

  <script src="./js/index.js"></script>
</body>

</html>
//entry.js
; ((doc, storage) => {
  const oUsername = doc.querySelector('#username')
  const oBtn = doc.querySelector('#btn')
  const init = () => {
    bindEvent()
  }
  function bindEvent() {
    oBtn.addEventListener('click', handleBtn, false)
  }
  function handleBtn() {
    const username = oUsername.value.trim()
    if (username.length < 6) {
      alert('用户名不能小于6位')
      return false
    }
    storage.setItem('username', username)
    location.href = 'index.html'

  }
  init()
})(document, localStorage)
; ((doc, storage) => {
  const oList = doc.querySelector('#list')
  const oMessage = doc.querySelector('#message')
  const oSendBtn = doc.querySelector('#sendBtn')
  const ws = new WebSocket('ws://localhost:8000')
  const init = () => {
    bindEvent()
  }
  function bindEvent() {
    oSendBtn.addEventListener('click', handleSend, false)
    // ws.addEventListener('open', handleOpen)
    ws.onopen = handleOpen
    ws.addEventListener('close', handleClose)
    ws.addEventListener('error', handleError)
    ws.addEventListener('message', handleMessage)
  }
  function handleSend() {
    const message = oMessage.value
    if (!message.trim()) {
      return false
    }
    ws.send(JSON.stringify({
      username: storage.getItem('username'),
      time: new Date().getTime(),
      message
    }))
    oMessage.value = ''
  }
  function handleOpen() {
    console.log('FE: websocket open')
  }
  function handleClose() {
    console.log('FE: websocket close')
  }
  function handleError() {
    console.log('FE: websocket error')
  }
  function handleMessage(e) {
    console.log('FE: websocket message')
    console.log(e)
    const data = JSON.parse(e.data)
    const { username, time, message } = data
    const oLi = doc.createElement('li')
    oLi.innerHTML = `
      <p>
        <span>${username}</span>
        <i>${time}</i>
      </p>
      <p>消息:${message}</p>
    `
    oList.appendChild(oLi)
  }
  init()
})(document, localStorage)

后端

  1. open
  2. close
  3. error
  4. message
  5. connection
//index.js
const Ws = require('ws')
  ; ((ws) => {
    const server = new ws.Server({ port: 8000 })
    const init = () => {
      bindEvent()
    }
    function bindEvent() {
      server.on('open', handleOpen)
      server.on('close', handleClose)
      server.on('error', handleError)
      server.on('connection', handleConnection)
    }
    function handleOpen() {
      console.log('BE: websocket open')
    }
    function handleClose() {
      console.log('BE: websocket close')
    }
    function handleError() {
      console.log('BE: websocket error')
    }
    function handleConnection(ws) {
      console.log('BE: websocket connection')
      ws.on('message', handleMessage)
    }
    function handleMessage(e) {
      server.clients.forEach((c) => {
        c.send(e.toString())
      })
    }
    init()
  })(Ws)