Springboot集成WebSocket

一、引入依赖

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

二、配置类进行配置

1、注册netty服务端配置

@Configuration
@ConfigurationProperties(prefix = "websocket")
@Data
@EnableConfigurationProperties
public class WebSocketProperties {
    /**
     * 服务器url
     */
    private String url;
}

2.注册ws请求处理器

@Configuration
@Import(WebSocketProperties.class)
public class WebSocketConfig{
    /**
     * 注册一个扫描ServerEndpoint注解处理器
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3.注册客户端

@ClientEndpoint
@Slf4j
public class WebSocketClient {
    @OnOpen
    public void open(Session s) {
        log.info("客户端开启了");
    }
    @OnClose
    public void close(CloseReason c) {
        log.info("客户端关闭了"+ c.getReasonPhrase());

    }
    @OnError
    public void error(Throwable t) {
        log.info("客户端发生错误");
    }
    @OnMessage
    public void message(String message, Session session) {
        log.info("客户端获取到服务端的信息:"+ message);
    }
}

4.注册客户端配置

@Configuration
public class WebSocketClientConfig {
    @Autowired
    WebSocketProperties webSocketProperties;

    /**
     * 连接服务器端
     * @param userName
     * @return
     * @throws Exception
     */
    public Session connect(String userName) throws Exception {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        //设置消息大小最大为10M
        container.setDefaultMaxBinaryMessageBufferSize(10 * 1024 * 1024);
        container.setDefaultMaxTextMessageBufferSize(10 * 1024 * 1024);
        String uri = "ws://" + webSocketProperties.getUrl() + "/" + userName;
        return container.connectToServer(WebSocketClient.class, URI.create(uri));
    }

    /**
     * 发送信息
     * @param msg
     * @param userName
     * @throws Exception
     */
    public void sendMsg(String msg, String userName) throws Exception {
        Session session = connect(userName);
        session.getBasicRemote().sendText(msg);
    }
}

三、使用

1、启动类上加上websocket启动注解

@SpringBootApplication
@Slf4j
@EnableWebSocket
public class SpringBootExampleApplication {
    public static void main(String[] args){
        SpringApplication.run(SpringBootExampleApplication.class, args);
    }
}

2、websocket 配置

# websocket 配置
websocket:
  url: localhost:8080/websocket

3、服务端监听消息处理器

@ServerEndpoint("/websocket/{username}")
@Component
@Slf4j
public class WebSocketController {
    public static Map<String,Session> sessionMap = new HashMap<>();
    /**
     * 连接建立的时候
     * @param session
     * @param userName
     * @throws IOException
     */
    @OnOpen
    public void openConnetion(Session session, @PathParam("username")String userName) throws IOException {
        sessionMap.put(userName,session);
        log.info("检测到客户端{}上线了",userName);
        session.getBasicRemote().sendText(userName + "上线了");
    }

    /**
     * 接收消息的时候
     * @param session
     */
    @OnMessage
    public void message(Session session,String message,@PathParam("username") String userName){
        log.info("检测到客户端{}发来消息了:{}",userName,message);
        // 发送给其他的session信息
        sessionMap.forEach((k,v)->{
            if(!k.equals(userName)){
                try {
                    v.getBasicRemote().sendText("【"+ userName + "】:" + message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 客户端关闭
     * @param session
     */
    @OnClose
    public void close(Session session,@PathParam("username") String userName){
        log.info("客户{}下线了",userName);
        sessionMap.remove(userName);
    }

    @OnError
    public void error(Session session,Throwable throwable){
        log.info("检测到session{}出现错误了",session.getId());
        log.error(ExceptionUtil.printStackTrace((Exception) throwable));
    }
}

4、客户端发送ws协议数据控制器

@RestController
@RequestMapping("websocket")
@CrossOrigin
public class WebSocketClientController {
    /**
     * 发送信息
     */
    @Autowired
    WebSocketClientConfig myWebSocketClientConfig;
    @GetMapping("sendMsg")
    public AjaxResult sendMsg(String msg,String userName) throws Exception {
        myWebSocketClientConfig.sendMsg(msg, userName);
        return AjaxResult.success();
    }

    /**
     * 模拟获取用户名
     * @return
     */
    @GetMapping("getUserName")
    public AjaxResult getUserName(){
        return AjaxResult.success(RandomUtil.randomString(5));
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值