SpringBoot整合Websocket

1. SpringBoot作为服务端

作为服务端时,需要先导入websocket的依赖

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

创建WebSocketServer工具类

package com.newlinker.jiangyin.utils;

/**
* @author cyl
* @time 2023/7/21
*/
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; @Component
@ServerEndpoint(value = "/websocket")
public class WebSocketServer { // 客户端会话列表
private static final Map<String, Session> clientSessions = new ConcurrentHashMap<>(); @OnOpen
public void onServerOpen(Session session) {
// 客户端连接到本地 WebSocket 服务
System.out.println("Client connected: " + session.getId());
clientSessions.put(session.getId(), session);
} @OnMessage
public void onMessage(Session session, String message) {
// 处理客户端发送的消息
System.out.println("Received message from client " + session.getId() + ": " + message); // 示例:将收到的消息广播给所有客户端
//broadcast(message);
} @OnClose
public void onServerClose(Session session, CloseReason reason) {
// 客户端断开连接
System.out.println("Client " + session.getId() + " disconnected: " + reason);
clientSessions.remove(session.getId());
} @OnError
public void onError(Session session, Throwable throwable) {
// 客户端连接发生错误
System.out.println("WebSocket client error: " + throwable.getMessage());
clientSessions.remove(session.getId());
} // 发送消息给指定客户端
public void sendToClient(String clientId, String message) {
Session session = clientSessions.get(clientId);
if (session != null && session.isOpen()) {
session.getAsyncRemote().sendText(message);
}
} // 广播消息给所有客户端
public void broadcast(String message) {
for (Session session : clientSessions.values()) {
if (session.isOpen()) {
session.getAsyncRemote().sendText(message);
}
}
} // 关闭客户端连接
public void closeClientConnection(String clientId) {
Session session = clientSessions.get(clientId);
if (session != null && session.isOpen()) {
try {
session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Closing connection"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

添加Spring Bean配置

package com.newlinker.jiangyin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* @author cyl
* @time 2022/4/11
*/ @Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}

至此,SpringBoot已可作为服务端进行websocket连接测试,测试时的路径为:

ws://localhost:port/websocket

其中若SpringBoot配置了ssl证书可提供https访问,则应将websocket连接协议更改为wss

websocket路径中的"/websocket"由@ServerEndpoint注解决定,推荐使用在线测试,简单方便

2. SpringBoot作为客户端

作为客户端,推荐使用okhttp的依赖以及google的gson转换包(可与上方的依赖共存,不用担心)

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<!-- 非必须,可以使用其他JSON包进行处理 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>

创建WebSocketClient工具类

package com.newlinker.jiangyin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.newlinker.jiangyin.config.XingHuoConfig;
import com.newlinker.jiangyin.entity.ro.Payload;
import com.newlinker.jiangyin.entity.ro.ResponseData;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import javax.websocket.OnError;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; /**
* @author cyl
* @time 2022/4/11
*/
@Component
public class WebSocketClient extends WebSocketListener {
//注入你的WebSocketServer工具类
@Autowired
private WebSocketServer webSocketServer; private WebSocket webSocket; // 客户端连接其他服务器
public void connectToServer(String serverUrl) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(serverUrl).build();
webSocket = okHttpClient.newWebSocket(request, this);
} @Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response); } //收到消息时触发,核心逻辑
@Override
public void onMessage(WebSocket webSocket, String text) {
ResponseData responseData = GSON.fromJson(text, ResponseData.class);
//此处服务器返回的status值为0时代表连接正常,由接口具体情况而定,与协议无关
if (0 == responseData.getHeader().get("code").getAsInt()) {
Payload pl =GSON.fromJson(responseData.getPayload(), Payload.class);
JsonArray temp = (JsonArray) pl.getChoices().get("text");
JsonObject jo = (JsonObject) temp.get(0);
//解析结果后将内容转发给下游客户端,也可以使用sendMessage方法定向发送
webSocketServer.broadcast(jo.get("content").getAsString());
//如果不想每次发送消息时都主动连接,需要建立websocket心跳,这里每次收发消息都主动断开
webSocket.close(3, "客户端主动断开链接");
}
} else {
System.out.println("返回结果错误:\n" + responseData.getHeader().get("code") + " " + responseData.getHeader().get("message"));
}
} @Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
System.out.println("WebSocket连接失败:");
super.onFailure(webSocket, t, response);
System.out.println(response);
} @OnError
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket发生错误:" + throwable.getMessage());
} //可以在Controller中调用该方法进行websocket的手动发送以及参数调整
public void sendMessage(String word) {
connectToServer();
JsonObject frame = new JsonObject();
//根据自己的需求填充你的请求参数
//...
webSocket.send(frame.toString());
System.out.println(frame.toString());
}
}

SpringBoot整合Websocket,实现作为客户端接收消息的同时作为服务端向下游客户发送消息的更多相关文章

  1. springboot整合websocket实现一对一消息推送和广播消息推送

    maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  2. Springboot整合Websocket遇到的坑

    Springboot整合Websocket遇到的坑 一.使用Springboot内嵌的tomcat启动websocket 1.添加ServerEndpointExporter配置bean @Confi ...

  3. SpringBoot 整合 WebSocket

    SpringBoot 整合 WebSocket(topic广播) 1.什么是WebSocket WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向 ...

  4. springboot整合websocket原生版

    目录 HTTP缺点 HTTP websocket区别 websocket原理 使用场景 springboot整合websocket 环境准备 客户端连接 加入战队 微信公众号 主题 HTTP请求用于我 ...

  5. springboot整合websocket高级版

    目录 sockjs介绍 产生的原因 环境搭建 springboot整合sockjs 使用场景 聊天室开发 点对点通信 群聊 效果 总结 加入战队 微信公众号 上一章节我们说了websocket的优缺点 ...

  6. SpringBoot整合websocket简单示例

    依赖 <!-- springboot整合websocket --> <dependency> <groupId>org.springframework.boot&l ...

  7. spring集成webSocket实现服务端向前端推送消息

    原文:https://blog.csdn.net/ya_nuo/article/details/79612158 spring集成webSocket实现服务端向前端推送消息   1.前端连接webso ...

  8. Android消息推送的服务端

    2.Android消息推送 MQTT服务器采用mosquito  http://mosquitto.org/ PHP管理包采用phpmqttclient:https://github.com/toku ...

  9. WebService或HTTP服务端接收请求转发消息到另一个服务端-实现思路

    1.需求结构(WebService) A客户端<->B服务端<->C服务端 说明: a.在B服务端上面添加配置项(1.是否转发消息到C服务端:2.C服务端IP和端口): b.A ...

  10. 客户端 new socket时候 就像服务端发起连接了

    客户端 new socket时候  就像服务端发起连接了

随机推荐

  1. Nuxt3环境变量配置

    Nuxt3 正式发布还不到半年,在投入生产环境使用后,遇到了不少问题,很难找到合适的解决方案,其中环境变量配置就是其中一个,之前一直未能解决,最近要上持续集成,无法绕过这个问题,所以花了点时间研究了一 ...

  2. 目标检测(Object Detection)

    文章目录 目标检测(Object Detection) 一.基本概念 1. 什么是目标检测 2. 目标检测的核心问题 3. 目标检测算法分类 1)Tow Stage 2)One Stage 4. 目标 ...

  3. springboot升级过程中踩坑定位分析记录 | 京东云技术团队

    作者:京东零售 李文龙 1.背景 " 俗话说:为了修复一个小bug而引入了一个更大bug " 因所负责的系统使用的spring框架版本5.1.5.RELEASE在线上出过一个偶发的 ...

  4. Centos7.x 安装Chrome + Chrome driver

    一.安装Chrome 1.执行下面命令进行安装操作 yum install https://dl.google.com/linux/direct/google-chrome-stable_curren ...

  5. 是时候,升级你的 Windows 了「GitHub 热点速览」

    不知道多少小伙伴用着 Windows 操作系统,可能会有一个烦恼是有时候操作系统过慢,因为众多拖慢 Windows 系统的组件.Atlas 作为一个修改版的 Windows 系统,能极大提高操作系统运 ...

  6. 收藏!最全Linux思维导图

    收藏!最全Linux思维导图 目录 收藏!最全Linux思维导图 1. 认识 Linux 2. Linux 命令 3. Linux学习路径 4. Linux 桌面介绍 5. FHS:文件系统目录标准 ...

  7. OData WebAPI实践-Non-EDM模式

    前文说到了 EDM 与 OData 之间的关系,具有 EDM 的 OData 提供了强大的查询能力,但是 OData 并不必须要配置 EDM,我们也可以使用 Non-EDM 方案. Non-EDM 所 ...

  8. 2021-08-07:与数组中元素的最大异或值。给你一个由非负整数组成的数组 nums 。另有一个查询数组 queries ,其中 queries[i] = [xi, mi] 。第 i 个查询的答案是

    2021-08-07:与数组中元素的最大异或值.给你一个由非负整数组成的数组 nums .另有一个查询数组 queries ,其中 queries[i] = [xi, mi] .第 i 个查询的答案是 ...

  9. 2021-10-29:除自身以外数组的乘积。给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之

    2021-10-29:除自身以外数组的乘积.给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i ...

  10. wmi搜集一台计算机的硬件信息

    作用: Python搜集一台计算机的硬件信息,借助模块:wmi,这个模块只支持window操作系统. 安装: pip install wmi 导入: import wmi 实例 c = wmi.WMI ...