Springboot WebSocket开发

创建springboot项目

添加webSocket依赖

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

配置类

@Configuration
public class WebSocketConfig {
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

核心类


@ServerEndpoint("/test/{id}")	//连接路径
@Component 						//被spring扫描到
public class Demo {


	//建立连接时调用
	@OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String userName){}

	//关闭连接时调用
	@OnClose
    public void onClose(@PathParam(value = "id") String userName){}

	//接收消息时调用
	@OnMessage
    public void onMessage(Session session, String message) throws IOException{}

	//错误时调用
	@OnError
    public void onError(Session session, Throwable throwable){}
}

  1. @ServerEndpoint标注的核心类 无法 进行Spring依赖注入.
    解决方案:使用RedisUtils工具类

    @Component
    public class RedisUtil {
    
        public static RedisTemplate redisTemplate;
    
        @Autowired
        public void setRedisTemplate(RedisTemplate redisTemplate) {
            RedisUtil.redisTemplate = redisTemplate;
        }
    }
    
    //直接使用方法的静态变量
    RedisUtils.redisTemplate.opsForValue().set("key", "value");
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot WebSocket是一种基于Spring Boot框架的实时通信协议,它可以在Web应用程序中实现双向通信。使用SpringBoot WebSocket,我们可以轻松地开发分布式即时通讯群聊系统,适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 在使用SpringBoot WebSocket进行通信时,我们可以通过以下步骤来实现: 1. 首先,我们需要引入Spring Boot WebSocket和Redis相关的依赖项。这可以通过在项目的pom.xml文件中添加相应的依赖来实现。 2. 接下来,我们需要创建一个WebSocket配置类,该类需要继承自`WebSocketMessageBrokerConfigurer`接口,并重写其中的方法,以配置WebSocket的相关信息。 3. 在配置类中,我们可以定义一个`@MessageMapping`注解的方法,用于处理客户端发送的消息,并进行相应的逻辑处理。 4. 可以通过使用`@SendTo`注解将处理结果发送回客户端,实现双向通信。 5. 最后,我们需要在前端页面中使用JavaScript代码来建立WebSocket连接,并进行消息的发送和接收。 通过上述步骤,我们可以实现基于Spring Boot WebSocket的通信功能。同时,我们还可以使用在线测试工具来测试我们的WebSocket通信,例如:http://wstool.jackxiang.com/。在测试过程中,我们可以使用测试访问地址来发送和接收消息,例如:ws://192.168.0.115:50041/webSocket/1或wss://192.168.0.115:50041/webSocket/2。 总结起来,SpringBoot WebSocket是一种基于Spring Boot的实时通信协议,可以用于开发分布式即时通讯群聊系统。通过配置WebSocket和使用相关的技术,我们可以实现双向通信功能,并通过在线测试工具来进行测试和调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值