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 "发送成功";
    }
}
相关推荐
ACP广源盛139246256733 小时前
IX8024与科学大模型的碰撞@ACP#筑牢科研 AI 算力高速枢纽分享
运维·服务器·网络·数据库·人工智能·嵌入式硬件·电脑
Empty-Filled3 小时前
AI生成测试用例功能怎么测:一个完整实战案例
网络·人工智能·测试用例
码云数智-大飞4 小时前
本地部署大模型:隐私安全与多元优势一站式解读
运维·网络·人工智能
jinanwuhuaguo4 小时前
(第二十九篇)OpenClaw 实时与具身的跃迁——从异步孤岛到数字世界的“原住民”
前端·网络·人工智能·重构·openclaw
汤愈韬5 小时前
三种常用 NAT 的经典案例
网络协议·网络安全·security
等风来不如迎风去5 小时前
【win11】最佳性能:fix 没有壁纸,一直黑屏
网络·人工智能
Harvy_没救了5 小时前
【网络部署】 Win11 + VMware CentOS8 + Nginx 文件共享服务 Wiki
运维·网络·nginx
汤愈韬6 小时前
NAT Server 与目的Nat
网络·网络协议·网络安全·security
2401_873479406 小时前
断网时如何实时判断IP归属?嵌入本地离线库,保障风控不中断
运维·服务器·网络
7ACE7 小时前
Wireshark TS | TLP 超时时间
网络·网络协议·tcp/ip·wireshark·tcpdump