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

相关推荐
xurileidian3 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
斑鸠喳喳5 小时前
Spring IoC 之 BeanFactoryPostProcessor
java·spring
知识汲取者1 天前
HTTP、SSE、WebSocket:三个老技术的区别、场景与选型
websocket·http·ai
不得了zz1 天前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
会编程的吕洞宾1 天前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
CoderYanger2 天前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github
nice_lcj5202 天前
Spring 事务:声明式事务怎么生效
java·spring·面试·事务·transactional·传播机制
vx-程序开发2 天前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业
nice_lcj5202 天前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
nice_lcj5202 天前
Spring Boot 入门:几行配置怎么跑起来
java·spring boot·spring·面试·自动配置·起步依赖