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. BZ全景编辑器(KRPano全景可视化编辑器, 无需编写代码, 图形化制作全景漫游)

    软件简介 BZ全景编辑器是一款KRPano全景可视化编辑工具,下载安装即可使用,无需拥有任何KRPano代码基础,便可以制作生成精美的全景漫游作品. BZ全景编辑器群:882083973 最新版软件下 ...

  2. mpi转以太网连接200plc以太网监控同时与步科触摸屏通信

    西门子PLC200 226PLC转以太网通过PPI-ETH-XD1.0集中采集不占用编程口同时与步科触摸屏通信 现有设备及联网要求客户车间内有6台纺机设备,控制系统采用西门子PLC,型号为CPU226 ...

  3. 使用 gopkg.in/yaml.v3 解析 YAML 数据

    YAML(YAML Ain't Markup Language)是一种人类可读的数据序列化格式,常用于配置文件和数据交换.在 Go 语言中,你可以使用 gopkg.in/yaml.v3 包来解析和生成 ...

  4. .NET 数据库大数据 方案(插入、更新、删除、查询 、插入或更新)

    1.功能介绍 (需要版本5.0.45) 海量数据操作ORM性能瓶颈在实体转换上面,并且不能使用常规的Sql去实现 当列越多转换越慢,SqlSugar将转换性能做到极致,并且采用数据库最佳API 操作数 ...

  5. 基于 ACK Serverless 解锁你家萌宠的 AI 形象

    基于 ACK Serverless 解锁你家萌宠的 AI 形象详情      1. 计费说明 必看!!必看!!必看!! 本实验为付费体验,需要消耗账号费用.体验后若不再需要使用,请及时释放资源,避免持 ...

  6. SharedPreferences-PreferenceUtils

    SharedPreferences   easy use import android.content.Context; import android.content.SharedPreference ...

  7. Go接口 - 构建可扩展Go应用

    本文深入探讨了Go语言中接口的概念和实际应用场景.从基础知识如接口的定义和实现,到更复杂的实战应用如解耦与抽象.多态.错误处理.插件架构以及资源管理,文章通过丰富的代码示例和详细的解释,展示了Go接口 ...

  8. Windows没有足够信息,不能验证该证书",是因为该证书的颁发者

    Windows没有足够信息,不能验证该证书",无法验证该证书的颁发者 解决方案之一: 1.win+R:打开运行 2.输入 gpedit.msc,确定,打开组策略 3.选择:计算机配置---管 ...

  9. Java8新特性(Lambda表达式、Stream流、Optional类)等

    1. Lambda表达式由来 1 package java8; 2 3 public class EmployeeTest { 4 public static void main(String[] a ...

  10. 多巴胺所表达的prediction error信号

    Dopamine reward prediction-error signalling: a two-component response (Wolfram Schultz; NATURE REVIE ...