SpringBoot简单集成WebSocket(纯后端)
程序员文章站
2022-03-19 16:11:01
SpringBoot简单集成WebSocket引入依赖 com.alibaba fastjson 1.2.7 org.sprin...
SpringBoot简单集成WebSocket(纯后端)
- 引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 编写一个WebSocketConfig
package com.ksxx.test.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 编写一个ServerEncoder继承Encoder,这个编译器是为了可以发送对象信息
package com.ksxx.test;
import com.alibaba.fastjson.JSON;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
public class ServerEncoder implements Encoder.Text<Object> {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init(EndpointConfig arg0) {
// TODO Auto-generated method stub
}
@Override
public String encode(Object obj) {
return JSON.toJSONString(obj);
}
}
- 编写一个WebSocketBacklogServer (其中type为类型,可多种连接类型)
package com.ksxx.test;
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.concurrent.ConcurrentHashMap;
@ServerEndpoint(value="/websocket/{type}/{userId}", encoders = { ServerEncoder.class })
@Component
public class WebSocketBacklogServer {
//存放每个客户端对应的MyWebSocket对象。
private static ConcurrentHashMap<String, WebSocketBacklogServer> webSocketSet = new ConcurrentHashMap<String, WebSocketBacklogServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收userId
private Integer userId;
//类型 待办:backlog、消息数量:message、即时通讯:chat
private String type;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("userId") Integer userId,@PathParam("type") String type) {
this.session = session;
webSocketSet.put(type+","+userId,this); //加入set中
this.userId=userId;
this.type=type;
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
System.out.println(userId+type);
webSocketSet.remove(type+","+userId); //从set中删除
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到来自窗口"+userId+"的关于"+type+"信息:"+messag);
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 推送
*/
public void sendMessage(Object message) throws EncodeException,IOException {
this.session.getBasicRemote().sendObject(message);
}
/**
* 发送消息到所有客户端
* @param message
* @throws EncodeException
* @throws IOException
*/
public void sendMessageInAll(Object message) throws EncodeException,IOException {
for(WebSocketBacklogServer value : webSocketSet.values()) {
value.session.getBasicRemote().sendObject(message);
}
}
/**
* 指定给某个连接发送信息
* */
public static void sendInfo(Object message,Integer userId,String type) throws EncodeException,IOException {
webSocketSet.get(type+","+userId).sendMessage(message);
}
}
- 模拟客户端测试连接
测试地址: http://www.jsons.cn/websocket/
- 模拟客户端测试发送信息
- 服务端主动推送信息(对象类),创建一个Controller写一个测试方法测试调用一下即可
package com.ksxx.test.controller;
import com.ksxx.test.service.WebSocketBacklogServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("test")
public class TestController {
@RequestMapping("aa")
public void aa(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("age",13);
try {
WebSocketBacklogServer.sendInfo(jsonObject,1,"chat");
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文地址:https://blog.csdn.net/October_zhang/article/details/111886986
推荐阅读
-
基于SpringBoot+WebSocket搭建一个简单的多人聊天系统
-
SpringBoot集成WebSocket长连接实际应用详解
-
springboot 后台框架平台 mybatis 集成代码生成器 shiro 权限 websocket
-
超简单!asp.net core前后端分离项目使用gitlab-ci持续集成到IIS
-
详解springboot集成websocket的两种实现方式
-
SpringBoot2.0集成WebSocket实现后台向前端推送信息
-
PC端WebSocket springboot stompjs 简单的实现即时通讯
-
Springboot集成aop的简单使用
-
springboot集成webSocket
-
springboot集成websocket点对点推送、广播推送