springCloud使用webSocket(接收端)

此篇文章主要写的我们在springCloud中使用websocket时,接收端写的主要代码。

此篇是小白看的。并详细介绍了应该怎样测试websocket的接收。

以及如果我们需要有自己写的service注入时,在websocket中应该怎样注入。此处我注入的service是deviceService。

java 复制代码
import com.apex.iot.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
@ServerEndpoint("/iotDataWebsocket")
public class DataWebSocketService {

    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

	// 我们自己写的service不能直接注入,需要这样注入
    private static DeviceService deviceService;
    @Autowired
    public void setDeviceService(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("连接成功:{}", session.getId());
        sessionPool.put(session.getId(), session);
    }

    /**
     * 连接关闭调用的方法
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        String sessionId = session.getId();
        sessionPool.remove(sessionId);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public synchronized void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        try{
        	System.out.println(message);
            this.sendMessage(session.getId(), message);
        }catch (Exception e) {
            log.error("处理消息失败!服务端收到客户端[{}]的消息:{}", session.getId(), message);
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }



    /**
     * 发送消息
     * @param sessionId
     * @param message
     */
    public void sendMessage(String sessionId, String message) {
        Session session = sessionPool.get(sessionId);
        if(session != null) {
            synchronized (session) {
                try{
                	// 你自己的方法
                    String result = deviceService.getDeviceMsgByRedis(message);
                    session.getBasicRemote().sendText(result);
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("发送消息失败!", e);
                }
            }
        }else{
            log.error("没有找到sessionId:{}", sessionId);
        }
    }




}

应该怎样测试:

给大家两个链接,都是进行测试websocket的。因为我这边洗的都是后台,所以直接用网页进行测试:

java 复制代码
https://wstool.jackxiang.com/
http://websocket-test.com/

我用的最多的是第一个链接:https://wstool.jackxiang.com/

链接里是我们的服务器地址,比如我写的是

ws://localhost:30116/iotDataWebsocket

其中iotDataWebsocket是我们在websocket中定义的,就是在类上的@ServerEndpoint("/iotDataWebsocket")

这时候我们有时候会出现连接不上的问题。没关系,更改一下配置:

我们在application.yml中添加

java 复制代码
server:
  port: 30116
#  ignored-urls: /**/**
  ignored-urls: /iotDataWebsocket,/device/save,/device/getDeviceMsgById

在ignored-urls中,我们这几个方法可以直接通过网页访问

以上准备工作完成了,就可以进行测试了

我们点击测试工具的开启连接,出现open这一行绿色的字,就说明连接成功,

点击开始发送按钮,即可进行websocket的发送。当我们看到收到消息的时候,websocket的联调成功了。

相关推荐
默默前行的虫虫16 小时前
解决EMQX WebSocket连接不稳定及优化WS配置提升稳定性?
websocket
金牌归来发现妻女流落街头17 小时前
【从SpringBoot到SpringCloud】
java·spring boot·spring cloud
张3蜂17 小时前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
Coder_Boy_18 小时前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
7哥♡ۣۖᝰꫛꫀꪝۣℋ19 小时前
Spring-cloud\Eureka
java·spring·微服务·eureka
一灰灰blog20 小时前
Spring AI中的多轮对话艺术:让大模型主动提问获取明确需求
数据库·人工智能·spring
Java水解21 小时前
【JAVA 进阶】Spring AOP核心原理:JDK与CGLib动态代理实战解析
后端·spring
暮色妖娆丶21 小时前
Spring 源码分析 BeanFactoryPostProcessor
spring boot·spring·源码
闲人编程1 天前
使用FastAPI和WebSocket构建高性能实时聊天系统
websocket·网络协议·网络编程·fastapi·持久化·实时聊天·codecapsule
暮色妖娆丶1 天前
SpringBoot 启动流程源码分析 ~ 它其实不复杂
spring boot·后端·spring