Vue+Nodejs 使用WebSocket创建一个简易聊天室

文章目录

一、页面效果

二、架构流程

使用vue编写前端页面,nodejs处理服务端消息,WebSocket进行实时通信

三、技术细节

1.客户端

javascript 复制代码
<template>
    <div>
        <form onsubmit="return false">
            <textarea  id="responseTest"  style="width: 500px; height: 300px"  ></textarea>
            <br />
            <input  type="text"  name="message"  style="width: 300px"  :value="inputVal"  @input="input"  />
            <input type="button" value="发送消息" @click="send(inputVal)" />
            <input type="button" value="清空聊天记录" @click="clean" />
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
          inputVal: '欢迎来到二二得四的聊天室',
          socket:null
        }
    },
    methods: {
        testWebsocket() {
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket
            }
            if (window.WebSocket) {
                this.socket = new WebSocket('ws://localhost:8088/ws')
              this.socket.onmessage = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = ta.value + '\n' + event.data
                }
              this.socket.onopen = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = '连接开启!'
                }
                this.socket.onclose = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = '连接关闭!'
                }
            } else {
                alert('你的浏览器不支持WebSocket')
            }
        },
        input(e) {
            this.inputVal = e.detail.value
        },
        clean() {
            document.getElementById('responseTest').value = ''
        },
        send(message) {
            if (!window.WebSocket) {
                return
            }
          if (this.socket.readyState === WebSocket.OPEN) {
              this.socket.send(message)
            } else {
                alert('连接没有开启')
            }
        },
    },
    mounted() {
        this.testWebsocket()
    },
}
</script>

<style></style>

2. 服务端

使用的是nodejs

javascript 复制代码
const ws = require('ws')

const webserve = new ws.Server({port:8088})

//打开WebSocket服务器:通过监听open事件打开服务器
webserve.on('open',function open() {
    console.log('connected')
})

//关闭WebSocket服务器:通过监听close事件关闭服务器
webserve.on('close',function close() {
    console.log('disconnected')
})

//监听连接:ws通过connection事件来监听连接
webserve.on('connection',function connection(res,req) {
    const ip1 =  req.headers['x-forwarded-for'] || req.socket.remoteAddress
    const port1 = req.socket.remotePort
    const clientName = ip1+port1
    console.log('连接已开启,开始发送消息')

    // 发送数据:ws通过send()方法来发送到客户端数据
    // res.send('welcome,'+clientName)

  //接收数据:ws通过message事件来接收数据。当客户端有消息发送给服务器时,服务器就能够触发该消息
    res.on('message',function incoming(message) {
        console.log('received: %s from %s',message,clientName)

        /**
         * 准备的状态:ws中WebSocket类具有以下4中准备状态
         * 1、CONNCETION:值为0,表示连接还没有打开
         * 2、OPEN:值为1,表示连接已经打开,可以通信了
         * 3、CLOSING:值为2,表示连接正在关闭
         * 4、CLOSED:值为2,表示连接已经关闭
         */
        webserve.clients.forEach(function each(client) {
            if(client.readyState === ws.OPEN){
                client.send(message.toString())
            }
        })
    })
})
相关推荐
源码获取_wx:Fegn089511 分钟前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视15 分钟前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan25 分钟前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL1 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
hashiqimiya2 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
零度@3 小时前
Java中Map的多种用法
java·前端·python
yuanyxh3 小时前
静默打印程序实现
前端·react.js·electron
三十_A4 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
小满zs5 小时前
Next.js第十三章(缓存组件)
前端