WebSocket原生实现

WebSocket-Vue2

WebSocket-Vue3

Vue2版本实现

前端实现

  • 目录结构
    在这里插入图片描述
  • login.vue 登录
<template>
  <div>
    <input type="text" placeholder="请输入用户名" v-model="userInfo.userName">
    <input type="text" placeholder="请输入密码" v-model="userInfo.passWord">
    <button @click="loginChat">进入聊天室</button>
  </div>
</template>

<script>
export default {
  name: 'Login',

  data () {
    return {
      userInfo: {
        userName: '',
        passWord: ''
      }
    }
  },

  mounted () {
  },

  methods: {
    loginChat () {
      console.log('userInfo', this.userInfo)
      // 做一些校验
      if (this.userInfo.userName === '' || this.userInfo.passWord === '') {
        return alert('用户名和密码为空')
      }
      localStorage.setItem('userName', this.userInfo.userName)
      this.$router.push('/home')
    }
  }
}
</script>

<style lang="less" scoped>

</style>

  • home.vue 聊天室
<template>
  <div>
    <div>
      <ul>
        <li v-for="(item, index) in msgList" :key="index">
        <p>
          <span>{{item.user}}</span>
          <span>{{new Date(item.dateTime)}}</span>
        </p>
        <p>{{item.msg}}</p>
        </li>
      </ul>
    </div>
    <hr>
    <input type="text" placeholder="请输入消息" v-model="msg">
    <button @click="handleSendMsg">发送</button>
  </div>
</template>

<script>
const ws = new WebSocket('ws:localhost:8000')

export default {
  name: 'home',

  data () {
    return {
      msg: '',
      msgList: [],
      userName: ''
    }
  },
  mounted () {
    this.bindEvent()
    this.userName = localStorage.getItem('userName')
    if (!this.userName) {
      this.$router.push('/login')
    }
  },

  methods: {
    handleSendMsg () {
      if (!this.msg.trim().length) {
        return alert('不能发送空消息')
      }
      ws.send(JSON.stringify({
        user: this.userName,
        msg: this.msg,
        dateTime: new Date()
      }))
    },
    bindEvent () {
      console.log('绑定事件')
      ws.addEventListener('close', this.handleClose.bind(this), false)
      ws.addEventListener('open', this.handleOpen.bind(this), false)
      ws.addEventListener('error', this.handleError.bind(this), false)
      ws.addEventListener('message', this.handleMessage.bind(this), false)
    },
    handleOpen () {
      console.log('open')
    },
    handleClose () {
      console.log('close')
    },
    handleError () {
      console.log('error')
    },
    handleMessage ({data}) {
      console.log('message', data)
      this.msgList.push(JSON.parse(data))
    }
  }
}
</script>

<style lang="less" scoped>

</style>

后台实现

  • 目录结构
    在这里插入图片描述

  • index.js

const Ws = require('ws').Server
;((Ws) => {
  // ws:localhost:8000
  const server = new Ws({
    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 (ws) {
    console.log('server open')
  }

  function handleClose (ws) {
    console.log('server close')
  }

  function handleError (ws) {
    console.log('server error')
  }

  function handleConnection (ws) {
    console.log('server connection')
    ws.on('message', handleMessag)
  }

  function handleMessag (msg) {
    console.log('msg', msg.toString())
    // 给所以客户端发送消息
    server.clients.forEach(c => {
      c.send(msg.toString())
    })
    console.log(server.clients)
  }
  init() 
})(Ws)

效果

在这里插入图片描述

在这里插入图片描述

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐