从零玩转Websocket实时通讯服务之前后端分离版本-websocket
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的更多相关文章
- 使用tomcat方式实现websocket即时通讯服务端讲解
使用tomcat方式实现websocket即时通讯服务端讲解 第一种方案:使用Tomcat的方式实现 tomcat版本要求:tomcat7.0+.需要支持Javaee7 导入javeee-api的ja ...
- Uniapp使用GoEasy实现websocket实时通讯
Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便. GoEasy上架DCloud Uniapp插件市场已经有一 ...
- 微信小程序使用GoEasy实现websocket实时通讯
不需要下载安装,便可以在微信好友.微信群之间快速的转发,用户只需要扫码或者在微信里点击,就可以立即运行,有着近似APP的用户体验,使得微信小程序成为全民热爱的好东西~ 同时因为微信小程序使用的是Jav ...
- Webapi实现websocket实时通讯
应用场景:前端页面发起一个websocket请求与后端进行实时通讯.后端监听某端口获取数据,将监听到的数据加工处理,通过websocket发送到前端. 这里只提供后台的处理方案仅供参考. 1.后端监听 ...
- 零配置Socket TCP消息通讯服务容器EC
EC全称是elastic communication,是基于c#实现的Socket网络通讯服务容器,支持windows .Net和mono.通过EC容器可以让开发人员在不了解Socket网络通讯知识和 ...
- 三分钟搭建websocket实时在线聊天,项目经理也不敢这么写
我们先看一下下面这张图: 可以看到这是一个简易的聊天室,两个窗口的消息是实时发送与接收的,这个主要就是用我们今天要讲的websocket实现的. websocket是什么? websocket是一种网 ...
- 使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯
前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交易,要开发此功能当时首先考虑到的就是swoole和workerman了,从网上大概了解了一下关于这两款 ...
- 【WebSocket No.1】实现服务端webSocket连接通讯
前言 现阶段socket通信使用TCP.UDP协议,其中TCP协议相对来说比较安全稳定!本文也是来讲解TCP为主(恕在下学艺不精). 下面是个人理解的tcp/ip进行通讯之间的三次握手! 1.客户端先 ...
- Django实现websocket完成实时通讯,聊天室,在线客服等
一 什么是Websocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在WebS ...
- 基于TP5使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯
https://www.cnblogs.com/wt645631686/p/7366924.html 前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交 ...
随机推荐
- 你知道Golang的模板怎么用吗?带你了解动态文本的生成!
Golang Template Go语言中的Go Template是一种用于生成文本输出的简单而强大的模板引擎.它提供了一种灵活的方式来生成各种格式的文本,例如HTML.XML.JSON等. Go T ...
- Solution -「九省联考 2018」IIIDX
Description Link. 给出一个堆,然后让你填数进去,使得其满足小根堆的性质,并使编号靠前的点的数最大. Solution 考虑贪心,把原数列降序排序,然后因为这个东西是整除分块的形式,所 ...
- DB2---创建返回结果集的函数
在数据验证中,经常遇到需返回结果集的操作,故整理一个返回结果集的DB2函数,便于后期查阅 1.准备测试表 /*创建测试表:设置结果集的属性为表字段*/ CREATE TABLE Test_EXWAST ...
- SQL连接符Left Join小实例
在一数据移植项目中,Left Join的应用 项目要求根据卡号获取最终用户号,规则如下: 1.根据card查询tbl_TestA表,获取userid,根据userid作为id查询tbl_TestB获 ...
- 汇编debug的安装
实验一查看CPU和内存,用机器指令和汇编指令编程 在做实验前需要debug命令. 工具:dosbox,debug.exe 安装:dosbox :https://www.dosbox.com/ debu ...
- Python面试题——面向对象题
1.简述面向对象的三大特性. 封装: 封装指的是把一堆数据属性与方法数据放在一个容器中,这个容器就是对象.让对象可以通过 "." 来调用对象中的数据属性与方法属性. 继承: 继承指 ...
- mol 文件格式简单解析(v2000)
前言 .mol 文件是常见的化学文件格式,主要包含分子的坐标.分子间的键等数据. 示例文件 下面是一个水分子的 .mol 文件 H2O APtclcactv05052315543D 0 0.00000 ...
- db-cdc之mysql 深入了解并使用binlog
1.什么是binlog? 2.binlog可以用来干什么? 3.怎么样使用binlog? binlog是记录所有数据库表结构变更(例如CREATE.ALTER TABLE-)以及表数据修改(INSER ...
- 【Unity3D】UI Toolkit样式选择器
1 前言 UI Toolkit简介 中介绍了样式属性,UI Toolkit容器 和 UI Toolkit元素 中介绍了容器和元素,本文将介绍样式选择器(Selector),主要包含样式类选择器(C ...
- InnoDB 存储引擎之 Buffer Pool
Mysql 5.7 InnoDB 存储引擎整体逻辑架构图 一.Buffer Pool 概述 InnoDB 作为一个存储引擎,为了降低磁盘 IO,提升读写性能,必然有相应的缓冲池机制,这个缓冲池就是 B ...