websocket集成文档

1.添加依赖

xml 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.添加配置

java 复制代码
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.添加websocket处理器

java 复制代码
@Setter@Getter
@ServerEndpoint("/{token}")
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<>();
    /**
     * 浏览器和服务器在建立连接
     * @param session
     * @param token
     */
    @OnOpen
    public void onOpen(Session session, @PathParam( "token") String token){
        System.out.println("客户端连接===>"+token);
        clients.put(token,session);
    }
    /**
     * 客户端发送消息
     * @param message
     * @param token
     */
    @OnMessage
    public void onMessage(String message, @PathParam( "token") String token){
        System.out.println("客户端:"+token+",发送消息:"+message);
        //发送消息
        clients.get(token).getAsyncRemote().sendText(message);
    }
    /**
     * 浏览器和服务器之间断开连接之后会调用此方法.
     * @param token
     */
    @OnClose
    public void onClose(@PathParam( "token") String token){
        System.out.println("客户端:"+token+",断开连接");
        //删除关系
        clients.remove(token);
    }
    /**
     * 通讯异常触发该事件
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}

4.提供接口获取浏览器发送的消息

java 复制代码
@RestController
public class MsgContoller {
    @RequestMapping("/sendMsg")
    public String sendMsg(String token,String msg) throws IOException {
        Session session = OrderWebSocketServer.clients.get(token);
        session.getBasicRemote().sendText(msg);
        return "发送成功";
    }
}
相关推荐
KaMeidebaby6 分钟前
卡梅德生物技术快报|原核膜蛋白表达优化实操手册,膜蛋白的纯化梯度洗脱完整流程
前端·网络·数据库·人工智能·算法
一只小菜鸡..1 小时前
Stanford CS144 学习笔记 (七):跨越虚实的边界——物理层、链路层与无线网络
网络·笔记·学习
且随疾风前行.1 小时前
Android Binder 驱动 - 内核驱动层源码初探
android·网络·binder
寒晓星1 小时前
【网络编程】UDP编程
linux·网络·网络协议·udp
逑之1 小时前
HTTP、HTTPS2
网络·网络协议·http
斌蔚司李2 小时前
Tp-link手动设置有线中继模式(图文版)
网络·智能路由器
运维大师2 小时前
【K8S 运维实战】03-网络模型实战CNI
运维·网络·kubernetes
_waylau3 小时前
Spring Framework HTTP服务客户端详解
java·后端·网络协议·spring·http·spring cloud
数智化管理手记4 小时前
全面预算管理执行偏差大?全面预算管理全流程落地步骤是什么
大数据·网络·数据库·人工智能·数据挖掘
爱刷碗的苏泓舒4 小时前
网络通信入门之 NTRIP、HTTP、TCP 与 IP 的关系:协议分层、连接过程以及实时数据流
网络协议·tcp/ip·http·网络通信·rtcm·监控运维·ntrip