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 "发送成功";
    }
}
相关推荐
ElevenS_it18811 小时前
Nginx日志监控告警实战:access_log解析+5xx突增+慢请求+异常IP自动告警完整方案(Filebeat+Zabbix)
运维·网络·tcp/ip·nginx·zabbix
狮子再回头12 小时前
relhat9.1 sshd配置
linux·服务器·网络
不爱编程的小陈13 小时前
深入解析 Go 网络 I/O 的底层引擎:从 epoll 到 netpoll
服务器·网络·golang
大草原的小灰灰13 小时前
TCP/IP协议栈传输层介绍
网络协议·tcp/ip
IT WorryFree14 小时前
FORTINET-CORE-MIB、FORTINET-FORTIGATE-MIB
网络
IT大白鼠14 小时前
IPv6过渡技术:原理、分类与应用
网络·网络协议·华为
IT WorryFree14 小时前
ESXi 全维度监控方式完整分类(按使用场景排序)
运维·服务器·网络
百度搜知知学社14 小时前
LockMyPix高级版|军事级加密守护你的私密数据
网络·移动安全·数据加密·隐私保护·安全软件
BAGAE14 小时前
星链卫星数据获取:从太空安全到实时通信的技术革命
网络·数据结构·数据库·算法·云计算·hbase
手握风云-15 小时前
ProtoBuf:从序列化原理到高性能架构底座(一)
java·网络·架构