springboot整合websocket实现客户端与服务端通信

2023-06-20,,

## 定义

 WebSocket是通过单个TCP连接提供全双工(双向通信)通信信道的计算机通信协议。此WebSocket API可在用户的浏览器和服务器之间进行双向通信。用户可以向服务器发送消息并接收事件驱动的响应,而无需轮询服务器。 它可以让多个用户连接到同一个实时服务器,并通过API进行通信并立即获得响应。

案例介绍

  后端在接收到用户新下的订单后,通知到后台系统

服务端代码

pom.xml

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

websocket配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* websocket配置
* @author : wang zns
* @date : 2019-05-06
*/
@Configuration
public class WebSocketConfig { @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} }

websocket核心业务类

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.LongAdder; /**
* websocket服务端核心类
* @author : wang zns
* @date : 2019-05-06
*/
@ServerEndpoint("/websocket")
@Component
@Slf4j
public class WebSocketService { /**
* 记录当前websocket的连接数(保证线程安全)
*/
private static LongAdder connectAccount = new LongAdder(); /**
*存放每个客户端对应的websocketServer对象(需保证线程安全)
*/
private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 与客户端的连接对象
*/
private Session session; /**
* 连接成功调用的方法
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
connectAccount.increment();
log.info("有新的连接接入,当前连接数为{}", connectAccount);
} /**
* 连接关闭时调用
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
connectAccount.decrement();
log.info("有连接关闭,当前连接数为{}", connectAccount);
} /**
* 收到客户端消息时调用
* @param message
*/
@OnMessage
public void onMessage(String message) {
log.info("收到客户端发来的消息,message -> {}", message);
} /**
* 服务端向客户端发送消息
* @param message
*/
public void sendMessage(String message) {
for (WebSocketService webSocketService : webSocketSet) {
try {
log.info("【websocket消息】 广播消息, message={}", message);
webSocketService.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.info("向客户端发送消息失败, {}", e.getMessage());
}
}
} }

客户端代码

在此案例中,我们的客户端为浏览器,所以直接通过js进行连接

<script>
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket('ws://127.0.0.1:9988/sell/websocket');
} else {
alert("你的浏览器暂不支持websocket,请更换其他浏览器再试");
} websocket.onopen = function (event) {
console.log("建立连接");
};
websocket.onclose = function (event) {
console.log("关闭连接");
};
websocket.onmessage = function (event) {
console.log("收到消息," + event.data);
// 弹窗提示与播放提示音乐
setTimeout(function () {
document.getElementById('notice').play();
},1000);
$("#orderModal").modal('show');
};
websocket.onerror = function (event) {
console.log("websocket异常");
};
/**
* readyState状态如下:
* CONNECTING:值为0,表示正在连接;
OPEN:值为1,表示连接成功,可以通信了;
CLOSING:值为2,表示连接正在关闭;
CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
*/ // 向服务端发送消息(必须为open状态时可发送)
if (websocket.readyState === 1) {
websocket.send("服务端你好");
} </script>

效果演示

服务端

客户端

写在最后

  websocket的作用远不止这些,本文只是一种较为常见的用法; 在最后附上参考的blog -> Spring Boot整合websocket实现群聊,点对点聊天

springboot整合websocket实现客户端与服务端通信的相关教程结束。

《springboot整合websocket实现客户端与服务端通信.doc》

下载本文的Word格式文档,以方便收藏与打印。