下载网站系统,办公室装修设计招商,wordpress 企业网站模板,分类信息网站怎么建设#x1f3a8;领域#xff1a;Java后端开发#x1f525;收录专栏#xff1a; 系统设计与实战 #x1f412;个人主页#xff1a;BreezAm #x1f496;Gitee#xff1a;https://gitee.com/BreezAm ✨个人标签#xff1a;【后端】【大数据】【前端】【运维】 文章目录领域Java后端开发 收录专栏 系统设计与实战 个人主页BreezAm Giteehttps://gitee.com/BreezAm ✨个人标签【后端】【大数据】【前端】【运维】 文章目录一、技术介绍1.1 客户端WebSocket1.1.1 函数1.1.2 事件1.2 服务端WebSocket二、实战2.1、服务端2.1.1引入maven依赖2.1.2 编写配置类2.1.3 编写WebSocketService服务类2.1.4 建立连接2.1.5 关闭连接2.1.6 发送消息2.1.7 监听错误2.2 客户端2.2.1 主页面2.2.1 聊天页面三、开源地址四、参考文献一、技术介绍
线上演示地址http://chat.breez.work 实时通信Instant Messaging简称IM是一个实时通信系统允许两人或多人使用网络实时的传递文字消息、文件、语音与视频交流。 场景再现
微信聊天QQ聊天网站在线客服
1.1 客户端WebSocket WebSocket 对象提供了用于创建和管理 WebSocket 连接以及可以通过该连接发送和接收数据的 API。使用 WebSocket() 构造函数来构造一个 WebSocket。 构造函数如下所示
const webSocket WebSocket(url[, protocols])例子如下
const webSocket new WebSocket(ws://42.193.120.86:3688/ws/小明/翠花)1.1.1 函数
1、 webSocket.send() 该函数用于向服务端发送一条消息例子如下
webSocket.send(Hello server!);2、 webSocket.close() 该函数用于关闭客户端与服务端的连接例子如下
webSocket.close();1.1.2 事件
1、webSocket.onopen 该事件用于监听客户端与服务端的连接状态如果客户端与服务端连接成功则该事件触发例子如下
webSocket.onopen function(event) {console.log(连接已经建立可以进行通信);
};2、webSocket.onclose 如果服务端与客户端连接断开那么此事件出发例子如下
webSocket.onclose function(event) {console.log(连接已经关闭);
};3、webSocket: message event 该事件用于监听服务端向客户端发送的消息例子如下
webSocket.addEventListener(message, function (event) {console.log(来自服务端的消息, event.data);
});4、webSocket:error event 如果客户端与服务端发生错误时那么此事件将会触发例子如下
webSocket.addEventListener(error, function (event) {console.log(连接出现错误, event);
});1.2 服务端WebSocket
ServerEndpoint用于声明一个socket服务例子如下
ServerEndpoint(value /ws/{userId}/{targetId})几个重要的方法注解
OnOpen 打开连接OnClose 监听关闭OnMessage 发送消息OnError 监听错误
二、实战
2.1、服务端
2.1.1引入maven依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId
/dependency2.1.2 编写配置类
Configuration
public class WebSocketConfig {Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}2.1.3 编写WebSocketService服务类
下面的userId代表发送者的ID号target代表发送目标ID号。
Component
ServerEndpoint(value /ws/{userId}/{target})
public class WebSocketService {//用于保存连接的用户信息private static ConcurrentHashMapString, Session SESSION new ConcurrentHashMap();//原子递增递减用于统计在线用户数private static AtomicInteger count new AtomicInteger();//消息队列用于保存待发送的信息private QueueString queue new LinkedBlockingDeque();//onOpen()//onClose()//onMessage()//onError()
}2.1.4 建立连接
建立连接之前判断用户是否已经连接如果没有连接那么将用户session信息保存到集合然后计数器递增。 OnOpenpublic void onOpen(Session session, PathParam(userId) String userId) {if (!SESSION.containsKey(userId)) {SESSION.put(userId, session);count.incrementAndGet();}}2.1.5 关闭连接
关闭连接的时候将用户session删除和计数器递减。 OnClosepublic void onClose(PathParam(userId) String userId) {SESSION.remove(userId);count.decrementAndGet();}2.1.6 发送消息
发送采用的方法是session.getBasicRemote().sendText(你好); OnMessagepublic void onMessage(String message, PathParam(userId) String userId, PathParam(target) String target) throws IOException {queue.add(message);Session s SESSION.get(target);if (s null) {Session b SESSION.get(userId);b.getBasicRemote().sendText(对方不在线);} else {for (int i 0; i queue.size(); i) {String msg queue.poll();Message m new Message();m.setUserId(userId);s.getBasicRemote().sendText(msg);}}}2.1.7 监听错误
出现错误删除用户session信息和计数器递减 OnErrorpublic void onError(Throwable error, PathParam(userId) String userId) {SESSION.remove(userId);count.decrementAndGet();error.printStackTrace();}2.2 客户端
本案例中客户端采用Nuxt编写相关代码如下
2.2.1 主页面
运行截图如图所示
templatediv stylepadding-left: 20%;div stylepadding-left: 20%;padding-top: 30px;div stylefont-size: 30px;欢迎使用喵喵号聊天/div/divdiv stylepadding-top: 20%;el-form :rulesrules refformInline :inlinetrue :modelformInline classdemo-form-inlineel-form-item label我的喵喵号 propuserIdel-input v-modelformInline.userId placeholder喵喵号/el-input/el-form-itemel-form-item label对方喵喵号 proptargetIdel-input v-modelformInline.targetId placeholder喵喵号/el-input/el-form-itemel-form-itemel-button typeprimary clickonSubmit(formInline)聊一下/el-button/el-form-item/el-form/div/div
/templatescriptexport default {name: IndexPage,data() {return {formInline: {userId: ,targetId: },rules: {userId: [{required: true,message: 请输入你的喵喵号,trigger: blur}],targetId: [{required: true,message: 请输入对方喵喵号,trigger: blur}]}}},methods: {onSubmit(formName) {this.$refs[formName].validate((valid) {if (valid) {this.$router.push({name: chat,params: this.formInline})} else {console.log(error submit!!);return false;}});}},created() {}}
/script
stylebody {background: url(../static/img/cat.jpg);}
/style
2.2.1 聊天页面
运行截图如下 小明
翠花
templatedivel-row :gutter20 stylepadding-top: 20px;div stylepadding-left: 35%;div stylepadding-bottom: 15pxdiv stylefloat: left;padding-right: 30px;我的喵喵号el-tag typewarning{{user.userId}}/el-tag/divdiv对方喵喵号el-tag typesuccess{{user.targetId}}/el-tagel-link clickclearMsg() :underlinefalse stylepadding-left: 30px; typedanger清空消息/el-link/div/divdiv styleborder: 1px green solid;width: 400px;height: 400px;border-radius: 10px;div v-for(m,index) in msgList :keyindexel-row :gutter20div v-ifm.type1 stylepadding-left: 10px;el-avatar srchttps://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png/el-avatar{{m.msg}}/divdiv v-ifm.type2 stylepadding-right: 15px;float: right;{{m.msg}}el-avatar srchttps://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg/el-avatar/divdiv v-ifm.type3 stylepadding-left: 15px;padding-top: 15px;系统消息{{m.msg}}/div/el-row/div/div/div/el-rowel-row :gutter5 stylepadding-top: 20px;padding-left: 35%;el-col :span9 :xs9 :sm9 :md9 :lg9 :xl9el-input :disabledmsg_status v-modelmsg placeholder消息/el-input/el-colel-col :span2el-button clicksendMessage() typeprimary发送/el-button/el-col/el-row/div/templatescriptexport default {name: ChatPage,data() {return {url: localhost:3688/ws/1001/1002,msg: ,socket: {},msg_status: true,msgList: [],initList: [],count: 0,user: {userId: ,targetId: }}},created() {const userId this.$route.params.userIdconst targetId this.$route.params.targetIdif (userId ! undefined targetId ! undefined) {this.user.userId userIdthis.user.targetId targetIdthis.connect()} else {this.$router.push(/)}},methods: {//创建socket客户端connect() {var that thisthis.socket new WebSocket(ws://42.193.120.86:3688/ws/ this.user.userId / this.user.targetId);this.socket.onclose function(event) {that.$message(连接关闭);};this.socket.addEventListener(error, function(event) {that.$message.error(出现错误);});// 监听消息this.socket.addEventListener(message, function(event) {that.msgList.push({type: 2,msg: event.data})console.log(event.data);console.log({type: 2,msg: event.data});});this.socket.onopen function(event) {that.msg_status falsethat.msgList.push({type: 3,msg: 连接成功})};},clearMsg() {this.$confirm(确认清空?, 提示, {confirmButtonText: 确定,cancelButtonText: 取消,type: warning}).then(() {this.msgList []})},//发送消息sendMessage() {this.socket.send(this.msg)this.msgList.push({type: 1,msg: this.msg})this.msg }}}
/scriptstyle
/style
三、开源地址
Giteehttps://gitee.com/BreezAm/websocket演示地址http://chat.breez.work
四、参考文献
MDNWebSocketNuxthttps://nuxtjs.orgVuehttps://cn.vuejs.org百度百科及时通信 收录专栏系统设计与实战