最近学习了一下websocket的即时通讯,感受很是的强大,这里我用node启动了一个服务进行websocket连接,而后再vue的view里面进行了连接,进行通讯,废话很少说,直接上代码吧,css
首先,我须要用到node的nodejs-websocket模块前端
使用yarn进行安装vue
yarn add nodejs-websocket --save
固然,你也能够用npm进行安装java
npm i nodejs-websocket --save
安装完毕以后,咱们开始写服务端的代码,首先,我用node在本地起了一个node服务器用来开启websocket服务node
sock.js:web
let ws = require("nodejs-websocket"); console.log("开始创建连接"); ws.createServer(function (conn) { conn.on("text", function (str) { console.log("收到的信息为", str); conn.send(`${str}(机器人`) }); conn.on("close", function (code, reason) { console.log("关闭链接") }); conn.on("error", function (code, reason) { console.log("异常关闭") }) }).listen(8001); console.log("连接创建完毕");
服务端主要是用nodejs-websocket用来开启服务,以及返回前端须要的值,这里我只是作了一个简单的处理,在接受值得后面加了一个‘机器人’的string,npm
而后,咱们须要开启这个node服务,数组
命令后面的路径必定要找对,我是把sock.js放在了根目录的socket文件夹下面服务器
执行websocket
yarn socket
最后,看咱们的客户端,客户端我是想有一个输入框,而后有个聊天框:
<template> <div class="test3"> <div class="msg" ref="box"> <div v-for="item in list" :class="[item.type,'msg-item']"> <p> {{item.content}} </p> </div> </div> <div class="input-group"> <input type="text" v-model="contentText"> <button @click="sendText">发送</button> </div> </div> </template> <script> export default { name: "index3", data() { return { list: [],//聊天记录的数组 contentText: "",//input输入的值 } }, methods: { //发送聊天信息 sendText() { let that = this; this.list = [...this.list, {type: "mine", content: this.contentText}];//经过type字段进行区分是本身(mine)发的仍是系统(robot)返回的 this.backText(function () { that.contentText = "";//加回调在获得返回数据的时候清除输入框的内容 }); }, backText(callback) { let that = this; if (window.WebSocket) { let ws = new WebSocket("ws://192.168.11.169:8001"); ws.onopen = function (e) { console.log("连接服务器成功"); console.log("that.contentText is", that.contentText); ws.send(that.contentText); callback(); }; ws.onclose = function (e) { console.log("服务器关闭") }; ws.onerror = function () { console.log("服务器出错") }; ws.onmessage = function (e) { that.list = [...that.list, {type: "robot", content: e.data}] } } } }, watch: { //监听list,当有修改的时候进行div的屏幕滚动,确保能看到最新的聊天 list: function () { let that = this; setTimeout(() => { that.$refs.box.scrollTop = that.$refs.box.scrollHeight; }, 0); //加setTimeout的缘由:因为vue采用虚拟dom,我每次生成新的消息时获取到的div的scrollHeight的值是生成新消息以前的值,因此形成每次都是最新的那条消息被隐藏掉了 } }, mounted() { } }; </script> <style scoped lang="scss"> .test3 { text-align: center; } .msg { width: 100px; height: 100px; overflow: auto; padding-top: 5px; border: 1px solid red; display: inline-block; margin-bottom: 6px; .msg-item { position: relative; overflow: hidden; p { display: inline-block; border-radius: 40px; background: #3C3D5A; color: white; float: left; padding: 2px 12px; margin: 0 0 2px 0; max-width: 70%; text-align: left; box-sizing: border-box; } &.mine { p { float: right; background: aquamarine; color: white; } } } } </style>
看一下最终效果: