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 "发送成功";
    }
}
相关推荐
绝世剑仙纪宁1 小时前
TCP 三次握手、四次挥手
网络·网络协议·tcp/ip
索迪迈科技1 小时前
HTTP中Payload的含义解析
网络·网络协议·http
时空潮汐2 小时前
我用神卓 NAT 公网 IP 盒子搭建《我的世界》联机的经历
网络·网络协议·tcp/ip
liulilittle2 小时前
HTTP/3.0:网络通信的技术革新与性能飞跃
网络·网络协议·http·https·quic·流媒体·通信
岑梓铭2 小时前
计算机网络第四章(4)——网络层《ARP协议》
网络·笔记·tcp/ip·计算机网络·考研·408
Linux运维技术栈3 小时前
域名网页加载慢怎么解决:从测速到优化的全链路性能优化实战
运维·网络·nginx·性能优化·cloudflare
北极光SD-WAN组网3 小时前
基于智能组网设备的港口网络安全闭环管控方案设计与实践
网络·安全·web安全
妳人話3 小时前
TCP的三次握手和四次挥手
网络·网络协议·tcp/ip
纳祥科技3 小时前
分享:一种为蓝牙、WIFI、U段音频发射设备提供ARC回传数字音频桥接功能的方案
网络·单片机·音视频
2501_916013744 小时前
HTTPS 抓包难点分析,从端口到工具的实战应对
网络协议·http·ios·小程序·https·uni-app·iphone