title: 从零玩转Websocket实时通讯服务之前后端分离版本
date: 2021-10-25 00:47:12.945
updated: 2021-12-26 17:43:10.496
url: https://www.yby6.com/archives/websocket
categories:
- OSS
- mysql
- api
- 单例模式
- websokcet
tags:

前言

公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.

后端搭建

一、依赖导入

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

二、搭建websocket服务

1.WebSocketConfig配置文件
/*==============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
=============================================================================*/ package top.yangbuyi.service_websocket.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* 配置文件
*
* @author Yang Buyi
* @date 2021/10/25
*/
@Configuration
public class WebSocketConfig { /**
* 给Spring容器注入 ServerEndpointExporter 对象
*
* @return {@link ServerEndpointExporter}
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.WebSocketServer服务
/*==============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
=============================================================================*/ package top.yangbuyi.service_websocket.server; import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet; /**
* websocket前端请求服务地址
*
* /service_websocket/wspoint/yangbuyi
*
* @author Yang Buyi
* @date 2021/10/25
*/
@ServerEndpoint("/service_websocket/wspoint/{loginName}")
@Component
public class WebSocketServer { /**
* 存储每一个连接
*/
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>(); /**
* 会话
*/
private Session session; /**
* 登录名
*/
private String loginName = ""; /**
* 在开放
*
* @param session 会话
* @param loginName 登录名
*/
@OnOpen
public void onOpen(Session session, @PathParam("loginName") String loginName) {
// 前端连接得到登陆名称
this.loginName = loginName;
// 当前websokcet生成的会话
this.session = session;
webSocketSet.add(this);
try {
sendMessage("success");
} catch (Exception ex) {
ex.printStackTrace();
}
} /**
* 在关闭
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
} /**
* 在消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("接收到来自[" + message + "]发送的消息" + session);
// 发送消息
// for (WebSocketServer item : webSocketSet) {
// try {
// item.sendMessage(message + ",时间:" + new Date() + session);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
} /**
* 在错误
*
* @param session 会话
* @param error 错误
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
} /**
* 发送消息
*
* @param message 消息
*/
public void sendMessage(String message) {
try {
if (this.session != null) {
this.session.getBasicRemote().sendText(message);
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 发送信息
* 发送指定消息给某个用户
*
* @param userName 用户名
* @param msgStr 消息信息
*/
public static void sendInfo(String userName, String msgStr) {
for (WebSocketServer item : webSocketSet) {
if (item.loginName.equals(userName)) {
item.sendMessage(msgStr);
}
}
}
}

自己写个controller

进行调用测试服务端消息发送

    /***
* userName 用户唯一标识 看你业务来 用户名称 用户id 都可以
*/
@GetMapping("/sendMessage")
public String sendMessage(String userName) {
// 发送消息提示到前端
WebSocketServer.sendInfo("这里是服务端发送的消息", userName);
return "yes";
}

前端搭建

一、index.vue

<!--============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
===========================================================================--> <template>
<div class="webSocket">
<button id="send" class="btn btn-default" @click="sendMsg('发送杨不易https://yangbuyi.top')">Send</button>
<div v-for="item in msgData" :key="item">
{{ item }}
</div>
</div>
</template>
<script> export default {
name: 'WebSocket',
data() {
return {
// 消息
msgData: [],
websocket: null
}
},
mounted() {
this.connection()
// this.initWebSocket()
},
destroyed() {
if (this.websocket != null) this.websocket.close() // 离开路由之后断开websocket连接
},
methods: {
initWebSocket() {
this.connection()
// const that = this
// // 断开重连机制,尝试发送消息,捕获异常发生时重连
// this.timer = setInterval(() => {
// try {
// that.websocket.send('hello')
// } catch (err) {
// console.log('断线了: ' + err)
// that.connection()
// }
// }, 5000)
}, /**
* 连接后台ws
*/
connection() {
const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称'
if (typeof (WebSocket) === 'undefined') {
console.log('您的浏览器不支持WebSocket')
this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!')
} else {
this.websocket = new WebSocket(socketUrl)
console.log(this.websocket)
this.websocket.onopen = this.websocketOnopen // 连接成功
this.websocket.onmessage = this.websocketOnmessage // 广播成功
this.websocket.onerror = this.websocketOnerror // 连接断开,失败
this.websocket.onclose = this.websocketClose // 连接关闭
}
},
websocketOnopen() {
this.sendMsg('连接成功第一次https://yangbuyi.top')
console.log('连接成功')
},
websocketOnerror() {
console.log('连接失败')
},
websocketClose() {
console.log('断开连接')
},
websocketOnmessage(data) {
// 接收 服务端来的数据
this.msgData.push(data)
},
sendMsg(val) {
this.websocket.send(val)
}
}
}
</script>

测试调用创建的controller 向前端发送消息

从零玩转Websocket实时通讯服务之前后端分离版本-websocket的更多相关文章

  1. 使用tomcat方式实现websocket即时通讯服务端讲解

    使用tomcat方式实现websocket即时通讯服务端讲解 第一种方案:使用Tomcat的方式实现 tomcat版本要求:tomcat7.0+.需要支持Javaee7 导入javeee-api的ja ...

  2. Uniapp使用GoEasy实现websocket实时通讯

    Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便. GoEasy上架DCloud Uniapp插件市场已经有一 ...

  3. 微信小程序使用GoEasy实现websocket实时通讯

    不需要下载安装,便可以在微信好友.微信群之间快速的转发,用户只需要扫码或者在微信里点击,就可以立即运行,有着近似APP的用户体验,使得微信小程序成为全民热爱的好东西~ 同时因为微信小程序使用的是Jav ...

  4. Webapi实现websocket实时通讯

    应用场景:前端页面发起一个websocket请求与后端进行实时通讯.后端监听某端口获取数据,将监听到的数据加工处理,通过websocket发送到前端. 这里只提供后台的处理方案仅供参考. 1.后端监听 ...

  5. 零配置Socket TCP消息通讯服务容器EC

    EC全称是elastic communication,是基于c#实现的Socket网络通讯服务容器,支持windows .Net和mono.通过EC容器可以让开发人员在不了解Socket网络通讯知识和 ...

  6. 三分钟搭建websocket实时在线聊天,项目经理也不敢这么写

    我们先看一下下面这张图: 可以看到这是一个简易的聊天室,两个窗口的消息是实时发送与接收的,这个主要就是用我们今天要讲的websocket实现的. websocket是什么? websocket是一种网 ...

  7. 使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯

    前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交易,要开发此功能当时首先考虑到的就是swoole和workerman了,从网上大概了解了一下关于这两款 ...

  8. 【WebSocket No.1】实现服务端webSocket连接通讯

    前言 现阶段socket通信使用TCP.UDP协议,其中TCP协议相对来说比较安全稳定!本文也是来讲解TCP为主(恕在下学艺不精). 下面是个人理解的tcp/ip进行通讯之间的三次握手! 1.客户端先 ...

  9. Django实现websocket完成实时通讯,聊天室,在线客服等

    一 什么是Websocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在WebS ...

  10. 基于TP5使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯

    https://www.cnblogs.com/wt645631686/p/7366924.html 前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交 ...

随机推荐

  1. KRPANO资源分析工具下载720THINK全景图

    提示:目前分析工具中的全景图下载功能将被极速全景图下载大师替代,相比分析工具,极速全景图下载大师支持更多的网站(包括各类KRPano全景网站,和百度街景) 详细可以查看如下的链接: 极速全景图下载大师 ...

  2. 谷粒商城微服务分布式高级篇:linux下使用docker安装ElasticSearch

    [root@localhost ~]# docker pull elasticsearch:7.8.0 安装elasticsearch:7.8.0[root@localhost ~]# docker ...

  3. Windows上Dart安装

    过程 *1 去github上下载一个release包或者直接将flutter通过git clone下来 *2 将下载下来的flutter/bin添加到path中 *3 此时运行flutter或者flu ...

  4. PLC通过Modbus转Profinet网关与合康变频器Modbus通讯案例

    PLC通过Modbus转Profinet网关(XD-MDPN100)与合康变频器Modbus通讯,实现了两个设备之间的数据交互.Profinet是一种基于以太网的实时工控网络协议,而Modbus是一种 ...

  5. JUC并发编程(2)—synchronized锁原理

    目录 乐观锁和悲观锁介绍 synchronized用法介绍 synchronized和ReentrantLock的区别 经典8锁问题案例 从字节码角度分析synchronized实现 synchron ...

  6. Django-rest-framework框架——请求与响应、视图组件

    目录 一 请求与响应 1.1 Request 1.1.1.1 常用属性 1).data 2).query_params 1.2 Response 1.1.2.1 构造方式 1.1.2.2 常用属性 1 ...

  7. 空地一体化网络综述_Space-Air-Ground Integrated Network: A Survey

    摘要 空地一体化网络(SAGIN)主要解决的是单一网络下的局限性问题,此综述文章从网络设计.资源分配.到性能的优化,对近几年SAGIN的总结. 引言 受限于网络容量和覆盖范围,仅依靠地面通信系统无法在 ...

  8. Java中的对象到底是什么

    对象是现实世界中的一切物体(实体,或能够定义的东西) Smalltalk是第一个成功的面向对象的语言 在编程世界中,对象通过类来实例化:同一个类型的对象可以接受相同的消息 状态+行为+标识=对象 每个 ...

  9. 开发现代化的.NetCore控制台程序:(4)使用GithubAction自动构建以及发布nuget包

    前言 上一篇文章介绍了将 nuget 包发布到 Github Packages 上. 本文更进一步,使用 GitHub Action 搭建 CI/CD 流水线,进行 nuget 的自动构建和发布. G ...

  10. (Good topic)卡牌分组(3.27leetcode每日打卡)

    给定一副牌,每张牌上都写着一个整数. 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:  每组都有 X 张牌. 组内所有的牌上都写着相同的整数. 仅当你可选的 X &g ...