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的联调成功了。

相关推荐
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
Bingo_BIG2 天前
Java Spring框架:单表的查询、新增、修改、删除、导入、导出
java·spring·前后端
paopaokaka_luck2 天前
智慧社区综合服务小程序(人脸识别、AI问答、Echarts图形化分析)
前端·javascript·spring boot·spring·数据分析·echarts
牧瀬クリスだ2 天前
YAML配置详解:SpringBoot实战指南
java·spring·yml
需要8262 天前
JVM 内存区域与对象创建:一次 GC 从哪来
java·jvm·spring boot·spring·servlet·tomcat
hey you~2 天前
云客服SDK怎么接入网站和小程序?超详细接入步骤
websocket·小程序开发·api对接·企业通信·云客服sdk
paopaokaka_luck2 天前
考研政治刷题小程序(AI推荐题目、ECharts数据分析、章节练习与专项训练、模拟考试、错题本与收藏夹、学习打卡与目标管理、题库和组卷维护)
前端·javascript·spring boot·spring·数据分析·echarts
步行cgn2 天前
Spring 基于 XML 的自动装配:byType 详解
java·后端·spring
边境悍匪2 天前
蜗牛学苑 Java 智能体学习 Day46|贯穿项目 2 思维导图复盘
java·开发语言·vue.js·学习·spring
步行cgn3 天前
Spring c 命名空间注入详解
java·后端·spring