nodejs-websocket+vue实现简单的即时通讯

实现效果
nodejs-websocket+vue实现简单的即时通讯_第1张图片nodejs-websocket+vue实现简单的即时通讯_第2张图片

 

node片段

安装nodejs-websocket,运行命令npm install nodejs-websocket
创建server.js

const ws = require('nodejs-websocket');
const moment = require('moment');
const hostName = '127.0.0.1';
let clients = {};

// 向所有客户端广播,传输数据
function boardCast(obj){
    server.connections.forEach(function(conn){
        conn.sendText(JSON.stringify(obj));
    })
}

function getDate() {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}

var server = ws.createServer(function(conn){
    console.log('开始链接')
    conn.on("text", function (obj) {
            //字符串转对象
            obj = JSON.parse(obj);
            //添加新人数据
            if(obj.first==true){
                clients[obj.name] =obj
            }
            obj.date = getDate()
            obj.people = [];
            //防止key重复,导致JSON.stringify报错
            for(let i in clients){
                let item = {}
                item.username = clients[i].name
                obj.people.push(item)
            }
            boardCast(obj)
    })
    conn.on("close", function (code, reason) {
        console.log(conn,code, reason, "关闭连接")
        
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭",conn,code, reason)
    });
}).listen(8000)

接下来在所在文件夹运行命令“node serve.js”
 

vue片段

创建ws连接

       //初始化
       initWebSocket(){
              const wsSock ='ws://127.0.0.1:8000'   //node运行的本地地址
              this.websock = new WebSocket(wsSock)
              this.websock.onmessage = this.websockMessage;   //发送
              this.websock.onopen = this.websockOpen;       //连接
              this.websock.onerror = this.websockError;    //异常
              this.websock.onclose = this.websockClose;    //退出
              let data = {name:this.userName,first:true}
              this.mask = false;
              setTimeout(() => {
                   this.websockSend(JSON.stringify(data))
              }, 1000); 
        },
        // 连接
        websockOpen(){
            console.log('已连接')
        },
        // 接收
        websockMessage(e){
            console.log('接收',e)
            let msg = JSON.parse(e.data)
            // 新人加入
            if(msg.first == true){
                this.joinList.push(msg)
            }
            // 聊天信息
            else{
                this.detail.push(msg)
            }
            // 聊天成员
            this.people = msg.people
            
        },
        // 发送
        websockSend(data){
            this.websock.send(data)
        },
        // 断开
        websockClose(e){
            console.log('断开链接',e)
            this.joinList = []
            this.detail = []
            this.people = []
            this.$toast('聊天室已解散')
            this.mask = true
        },
        // 异常
        websockError(){
            console.log('异常断开')
        },
        // 提交发送内容
        sumbit(){
            if(this.text==""){
                 this.$toast('请输入发送内容')
                return false
            }
            let data = {name:this.userName,msg:this.text,first:false}
            this.websockSend(JSON.stringify(data))
            this.text =''
        }

HTML部分我就不贴,各位猿友自由发挥就可以了,很简单就实现了简单的即时通讯。有错误的地方,欢迎各位指点

你可能感兴趣的:(vue.js,websocket,前端,node)