Springboot http给websocket客户端发消息

web.xml导入

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

springboot可以使用一个端口即提供http服务,也可以作为websocket服务,取决于用什么协议来访问它

websocket配置


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    /**
     * 注册handle
     * @see org.springframework.web.socket.config.annotation.WebSocketConfigurer#registerWebSocketHandlers(org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry)
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(),"/").addInterceptors(new HttpSessionHandshakeInterceptor()).setAllowedOrigins("*");

    }

    @Bean
    public WebSocketHandler myHandler(){
        return new MyMessageHandler();
    }
}

如果跨域的话注意加上setAllowedOrigins("*");

在消息处理类中,建立连接后把session信息存在ConCurrentHashMap中

public class MyMessageHandler implements WebSocketHandler {
    public final static Map<String, WebSocketSession> userMap = new ConcurrentHashMap<String, WebSocketSession>();

    ......

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        String userId = this.getUserId(session);
        if (StringUtils.isNoneBlank(userId)) {
            userMap.put(userId, session);
            session.sendMessage(new TextMessage("建立服务端连接成功!"));
        }

    }

}

写一个http路由方法,通过调用map中session的sendMessage方法即可发送消息,如果需要获取异步返回值的话可以把返回值放到Redis里,再加一个方法通过获取redis里的状态值

 @ResponseBody
    @RequestMapping(value = "/sendcommand/{devId}",method = RequestMethod.POST)
    public Object sendcommand(@PathVariable(required = false) String devId,
                              @RequestHeader(value="token", required = false) String token,
                              @RequestBody String body, HttpServletResponse response
                     ) {
        WebSocketSession session = MyMessageHandler.getSession(devId);
        if (session != null && session.isOpen()) {
            try {
                TextMessage message = new TextMessage(body);
                session.sendMessage(message);

            } catch (IOException e) {
                e.printStackTrace();
                return new JsonError(e.getMessage());
            }
            return new JsonSuccess();
        }
        return new JsonError("offline");
    }

Spring Boot中监测WebSocket客户端断开连接,你可以使用`WebSocketSession`提供的方法和Spring的事件机制来实现。 首先,创建一个WebSocket处理器类,继承`TextWebSocketHandler`,重写相应的方法,例如: ```java import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; public class MyWebSocketHandler extends TextWebSocketHandler { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // 连接建立时触发 System.out.println("WebSocket连接已建立"); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // 连接关闭时触发 System.out.println("WebSocket连接已关闭,状态码:" + status.getCode() + ",原因:" + status.getReason()); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理接收到的消息 String receivedMessage = message.getPayload(); System.out.println("接收到消息:" + receivedMessage); } } ``` 然后,在你的Spring Boot应用程序中配置WebSocket,可以使用`@EnableWebSocket`注解启用WebSocket功能,并添加一个`WebSocketHandler` bean。例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @SpringBootApplication @EnableWebSocket public class MyApplication implements WebSocketConfigurer { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler(), "/websocket"); } @Bean public MyWebSocketHandler myWebSocketHandler() { return new MyWebSocketHandler(); } } ``` 在上面的示例中,`WebSocketHandlerRegistry`用于注册WebSocket处理器,并指定WebSocket的URL路径。`myWebSocketHandler()`方法返回我们创建的`MyWebSocketHandler`实例。 当客户端与服务器建立连接、关闭连接时,`MyWebSocketHandler`类中相应的方法将被调用,你可以在这些方法中处理相应的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值