express-ws实现客服聊天功能
express-ws实现webSocket通信
前言
最近要给自己写的项目中加一个客服聊天的功能。就是前端商城和后台管理系统通信。但是是两个不同的端口。
百度了一下就找到了webSocket。
什么是webSocket?
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。(来自菜鸟教程:https://www.runoob.com/html/html5-websocket.html)
express-ws实现
1、首先在express项目中安装express-ws
npm i express-ws --save
2、然后引入
const express = require('express')
const app = express()
// 引入WebSocket
const ws = require("express-ws")
// 将webSocket服务混入app,相当于为app添加.ws方法
ws(app)
3、启动服务
//为了获取到所以的客户端
const wss = ws(app).getWss('/')
// 建立webSocket服务
app.ws('/', (ws, req) => {console.log("连接成功!");// send给客户端发消息// on是监听事件// message表示服务端传来的数据ws.on("message", (msg) => {// 给所有的客户端广播消息wss.clients.forEach((e) => {e.send(msg)})})// close 事件表示客户端断开连接时执行的回调函数ws.on('close', function (e) {console.log('close connection')})})app.listen(3002, () => {console.log('success in port 3002,服务已经跑起来啦');
})
此时服务已经在3002端口跑起来了
前端接收消息
1、vue中
<script>//连接webSocket
const ws = new WebSocket('ws://localhost:3002')
export default {data () {return {msg: '',msgList: []}},mounted () {// 绑定webSocket事件//连接成功的回调ws.addEventListener('open', this.handleWsOpen.bind(this), false)//关闭的回调ws.addEventListener('close', this.handleWsClose.bind(this), false)//连接错误的回调ws.addEventListener('error', this.handleWsError.bind(this), false)//接收发送消息的回调ws.addEventListener('message', this.handleWsMessage.bind(this), false)},methods: {sendMessage () {const currentY = new Date().getFullYear()let currentM = new Date().getMonth() + 1let currentD = new Date().getDate()let currentH = new Date().getHours()let currentMin = new Date().getMinutes()let currentS = new Date().getSeconds()if (currentM < 10) {currentM = `0${currentM}`}if (currentD < 10) {currentD = `0${currentD}`}if (currentH < 10) {currentH = `0${currentH}`}if (currentMin < 10) {currentMin = `0${currentMin}`}if (currentS < 10) {currentS = `0${currentS}`}const date = `${currentY}-${currentM}-${currentD} ${currentH}:${currentMin}:${currentS}`const name = window.sessionStorage.getItem('nickname')const msg = JSON.stringify({msg: this.msg,name: name,date: date,left: true})ws.send(msg)// 发送完清空聊天框this.msg = ''},handleWsOpen () {console.log('聊天已经启动!')},handleWsClose () {console.log('聊天已经关闭!')},handleWsError () {console.log('聊天出错!')},// 收发消息handleWsMessage (e) {console.log(e)const msg = JSON.parse(e.data)this.msgList.push(msg)}}
}
</script>
2、react中
const ws = new WebSocket('ws://localhost:3002')
class Chat extends Component {constructor(props) {super(props)this.state = {msg: "",msgList:[]}}componentDidMount () {ws.addEventListener('open', this.handleWsOpen.bind(this), false)ws.addEventListener('close', this.handleWsClose.bind(this), false)ws.addEventListener('error', this.handleWsError.bind(this), false)ws.addEventListener('message', this.handleWsMessage.bind(this), false)}sendMessage = ()=> {const currentY = new Date().getFullYear()let currentM = new Date().getMonth() + 1let currentD = new Date().getDate()let currentH = new Date().getHours()let currentMin = new Date().getMinutes()let currentS = new Date().getSeconds()if (currentM < 10) {currentM = `0${currentM}`}if (currentD < 10) {currentD = `0${currentD}`}if (currentH < 10) {currentH = `0${currentH}`}if (currentMin < 10) {currentMin = `0${currentMin}`}if (currentS < 10) {currentS = `0${currentS}`}const date = `${currentY}-${currentM}-${currentD} ${currentH}:${currentMin}:${currentS}`const name = "客服"const msg = JSON.stringify({msg: this.state.msg,name: name,date: date,left: false})ws.send(msg)// 发送完清空聊天框this.setState({msg:""})}handleWsOpen () {message.success("连接成功")}handleWsClose () {message.info("聊天结束")}handleWsError () {message.error("连接失败")}// 收发消息handleWsMessage (e) {const msg = JSON.parse(e.data)let arr = this.state.msgListarr.push(msg)this.setState({msgList:arr})}render () {const msgList = this.state.msgListreturn (<ContentclassName="site-layout-background"><div className="chatBox"><div className="chat">{/* 展示消息 */}<div className="chat-info">{msgList.map((item, k) => {return <div className="info-detail"><div className={item.left?'head-a':'head'}><span className={item.left?'name-a':'name'}>{item.name}</span><span>{item.date}</span></div><div className={item.left?'info-main-a':'info-main'}><span>{item.msg}</span></div></div>})}</div>{/* 发送消息 */}<div className="send-msg"><Input value={this.state.msg} onChange={(e) => { this.setState({msg:e.target.value})}} placeholder="请输入..."style={{ width: "350px", marginRight: "10px" }}onPressEnter={() => {this.sendMessage()}}></Input><Button type="primary" onClick={() => {this.sendMessage()}}>发送</Button></div></div></div></Content >)}
}
效果如下:
vue全部代码
<template><div class="chat"><div class="chat-box"><div class="chat-info"><div class="info-detail" v-for="(item,k) in msgList" :key="k"><div :class="item.left?'head':'head-a'"><span class="name">{{item.name}}</span><span>{{item.date}}</span></div><div :class="item.left?'info-main':'info-main-a'"><span>{{item.msg}}</span></div></div></div><div class="chat-message"><el-input v-model="msg" placeholder="请输入内容" @keyup.enter.native="sendMessage" ><el-button slot="append" type="primary" @click="sendMessage" >发送</el-button></el-input></div></div></div>
</template><script>
const ws = new WebSocket('ws://localhost:3002')
export default {data () {return {msg: '',msgList: []}},mounted () {// 绑定webSocket事件ws.addEventListener('open', this.handleWsOpen.bind(this), false)ws.addEventListener('close', this.handleWsClose.bind(this), false)ws.addEventListener('error', this.handleWsError.bind(this), false)ws.addEventListener('message', this.handleWsMessage.bind(this), false)},methods: {sendMessage () {const currentY = new Date().getFullYear()let currentM = new Date().getMonth() + 1let currentD = new Date().getDate()let currentH = new Date().getHours()let currentMin = new Date().getMinutes()let currentS = new Date().getSeconds()if (currentM < 10) {currentM = `0${currentM}`}if (currentD < 10) {currentD = `0${currentD}`}if (currentH < 10) {currentH = `0${currentH}`}if (currentMin < 10) {currentMin = `0${currentMin}`}if (currentS < 10) {currentS = `0${currentS}`}const date = `${currentY}-${currentM}-${currentD} ${currentH}:${currentMin}:${currentS}`const name = window.sessionStorage.getItem('nickname')const msg = JSON.stringify({msg: this.msg,name: name,date: date,left: true})ws.send(msg)// 发送完清空聊天框this.msg = ''},handleWsOpen () {console.log('聊天已经启动!')},handleWsClose () {console.log('聊天已经关闭!')},handleWsError () {console.log('聊天出错!')},// 收发消息handleWsMessage (e) {console.log(e)const msg = JSON.parse(e.data)this.msgList.push(msg)}}
}
</script><style lang="less" scoped>
.chat {padding: 100px 300px 0 300px;
display: flex;
justify-content: center;
.chat-box{margin-top: 20px;
padding: 10px 10px 10px 10px;
width: 400px;
height: 600px;
background-color: #fff;
border-radius: 10px 10px 0 0 ;
.chat-info{height: 550px;overflow: auto;.info-detail{margin-bottom: 5px;.head{width: 100%;margin-bottom: 5px;display:flex;flex-direction: row-reverse;.name{margin-left: 5px;color: rgb(240, 74, 74);}}.head-a{width: 100%;margin-bottom: 5px;.name{margin-right: 5px;color: rgb(22, 189, 240);}}.info-main-a{font-size: 18px;font-family: 楷体;}.info-main{font-size: 18px;font-family: 楷体;display:flex;flex-direction: row-reverse;}}
}
.chat-message{height: 50px;
}
}
}</style>
express-ws实现客服聊天功能相关推荐
- java微信多客服_微信多客服聊天功能怎么实现?
原标题:微信多客服聊天功能怎么实现? 朋友小赵是很早的一批代购,微信号上添加了不少顾客.随着业务不断扩展,口碑越来越好,客户数量越来越多.经常有顾客在微信上咨询,日子久了,小赵就有点吃不消了.于是小赵 ...
- 融云api开发Java后台客服聊天功能(一)
以下所有内容均为本人自己开发总结的经验,如有雷同,不胜荣幸! 最近公司在做一款app,app里面涉及到与客服聊天功能. 于是公司就接入了融云api聊天系统. app端(前端)聊天由专业的ios and ...
- javaIO模型-Socket实现一个简单的客服聊天功能的改造(二)
功能改进-线程池 当然,先不考虑改端口合不合实际场景 我们想达到的流程是这样的: 再加上线程池,来在一个进程中启动多个服务端和多个客户端(当然因为控制台是唯一的,所以没办法模拟通信了). 话不多说,代 ...
- QQ客服聊天功能网页跳转只需要几行代码
<html><head><meta charset="utf-8"></head><body><a target= ...
- uniapp 微信小程序使用button调用在线客服聊天功能
亲测可用,若有疑问请私信 <button open-type="contact" style="border-radius: 0;display: flex;fle ...
- ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(四) 添加表情、群聊功能...
休息了两天,还是决定把这个尾巴给收了.本篇是最后一篇,也算是草草收尾吧.今天要加上表情功能和群聊.基本上就差不多了,其他功能,读者可以自行扩展或者优化.至于我写的代码方面,自己也没去重构.好的,我们开 ...
- php实现网站客服聊天/在线沟通功能
php实现网站客服聊天/在线沟通功能 这是后台页面 这是访客页面 前后端数据交互格式 JSON 前端框架 VUE Element UI JavaScript 后端技术 mysql 5.6 php 5. ...
- uni-app 微信小程序客服聊天和发送页面卡片功能
微信小程序客服聊天和发送页面卡片功能实现步骤如下: (一):首先登录微信公众平台 :https://mp.weixin.qq.com/ 登录成功后找到----->功能-----> 客服-- ...
- 基于webScoket的在线客服聊天
什么是webScoket WebSocket协议是基于TCP的一种新的网络协议.它实现了浏览器与服务器全双工(full-duplex)通信--允许服务器主动发送信息给客户端. 简单的说,WebSock ...
最新文章
- java实验报告二_Java实验报告(实验二)
- 扎克伯格成美国科技巨头里最后一位在任创始人CEO
- Gartner2018新技术成熟度曲线:五大技术趋势成为新热点
- [云炬创业管理笔记]第二章测试4
- 90题细品吴恩达《机器学习》,感受被刷题支配的恐惧
- python zope 工作流_使用C语言来扩展Python程序和Zope服务器的教程
- echarts柱状图的数据差距过大影响美观
- 【Luogu1160】队列安排(双向链表)
- 部署在IIS服务器的asp.net 网站,禁止访问指定类型文件
- springboot集成kafka_厉害!腾讯T3-2都还在学的微服务+MySQL+Kafka+boot2.x+虚拟机PDF
- 怎么扒站建站_个人怎么做独立站Shopify商店!Shopify建站教程详解!(实操干货)...
- ONENOTE注册CSDN
- 【移动安全高级篇】————2、浅谈Android软件安全自动化审计
- ​Copyright到底是什么意思?
- 一个软件公司需要多少前端_建一个微商城需要多少钱?
- 前端性能优化:7.页面渲染优化
- 《算法艺术与信息学竞赛》之 递推 例一 月亮之眼 vijos 1540
- 备战Java后端【Day6】
- 达梦数据库在ZYJ环境上通过RPM打包注册服务的步骤
- Chrome 75 lazy-loading