淘先锋技术网

首页 1 2 3 4 5 6 7

Vue实时通信 实现用webSocket长连接聊天功能

1.安装vue-cli
2.init 初始化项目
3.npm install ws(websocket)
4.文件夹中创建server.js

1、服务器代码

//index.js
//启动web服务,监听3000端口 绑定socket.io服务,接受websocket连接请求
const http = require('http').createServer();
const express = require('express')
// 创建websocket服务实例
var webSocket = require('ws')

var wss = new webSocket.Server({port:3000})
//监听客户端的连接事件
wss.on("connection",function(ws){
    console.log("新用户连接") 
    //接收前端的信息
    ws.on("message",function(data){
        wss.clients.forEach(function(client){
            //将信息广播
            client.send(data)
        })
    })  
})

  console.log('server is running...')

2、客户端页面代码

<template>
 <div class="home">
   <ul>
     <li v-for="item in msgList" :key="item.id">
       <p>消息:{{item.msg}}</p>
     </li>
   </ul>
   <input type="text" placeholder="在此输入消息" v-model="msg">
   <button @click="sendMessage()">发送</button>
 </div>
</template>
<script src="../scripts/socket.io.js"></script>
<script>
const ws = new WebSocket("ws://localhost:3000");
export default {
 data() {
   return {
      msg: '',
      msgList: []
   }
  
 },
 mounted() {
   ws.addEventListener("open", (e) => {
     console.log(e);
   });
   ws.addEventListener('close', (e) => {
       console.log(e);
     })
     ws.addEventListener('error', (e) => {
       console.log(e);
     })
     ws.addEventListener('message', (e) => {
       let self = this;
       const msg = JSON.parse(e.data)
       self.msgList.push(msg)
       console.log(self.msgList);
     })
 },
 methods: {
   sendMessage() {
     let self = this;
       ws.send(JSON.stringify({
         msg: self.msg
       }))
       self.msg = ''
   },
 },
};
</script>