(一)SpringBoot 整合WebSocket 前端 uniapp 访问

第一次使用WebSocket,所以最需要一个及其简单的例子,跑通之后,增加自己对该技术的理解。(技术基础介绍就免掉了,后面再补)

 案例逻辑:目前只有一个用户,而且是一个用户给服务器发送数据,服务给该用户返回数据

一、SpringBoot 整合 WebSocket

此处的逻辑一共三步

第一步,添加依赖项

第二步,添加配置

第三,写基础服务类

 1. 添加websocket依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!--需要版本的自己加-->
  </dependency>

2. 添加配置

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

3. 基础服务工具类


@ServerEndpoint(value = "/ws/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    private String userId;
    /**
     * @param session 是webSocket的会话对象,不是浏览器那个session
     * @param userId  用户Id
     * @description 当连接建立成功调用
     **/
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId = userId;
        System.out.println("建立连接");
    }
    /**
     * @param session 会话对象
     * @description 当连接关闭调用
     **/
    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("关闭连接");
    }

    /**
     * @param message 客户端发送的消息
     * @param session 会话对象
     * @description 当客户端发送消息时调用
     **/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        try{
            System.out.println(message);
           //给客户端发送消息
            session.getBasicRemote().sendText("服务端定义的消息");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

二、uniapp 构建webSocket与服务器通信

前端逻辑

第一步:跟服务器建立连接

第二步:监听WebSocket连接打开事件,并在这个监听事件中,主动给服务端发送数据

第三步:监听WebSocket接受到服务器的消息事件(你给服务器发送消息时,它也会及时给前端返回数据)

1. 具体代码


function webSocketFun(Integer userId){
    //1. 通过用户唯一id 与 服务端webSocket建立连接
    uni.connectSocket({
	    url: `http://192.168.2.18:8080/ws/${userId}`
    });


    //2. 监听WebSocket连接打开事件,并给服务端发送消息
    var socketOpen = false;
	var socketMsgQueue = ["滕","禹","鑫"];
    uni.onSocketOpen(function (res) {
		console.log('WebSocket连接已打开');
		socketOpen = true;
		for (var i = 0; i < socketMsgQueue.length; i++) {
			sendSocketMessage(socketMsgQueue[i]);
		}
		socketMsgQueue = [];
	});
	
	function sendSocketMessage(msg) {
	  if (socketOpen) {
	    uni.sendSocketMessage({
	      data: msg
	    });
	  } else {
	    socketMsgQueue.push(msg);
	  }
	}


    //3. 监听WebSocket接受到服务器的消息事件
    uni.onSocketMessage(function (res) {
	  console.log('收到服务器返回的内容为 ======' + res.data);
	});
}



 

### Spring Boot 整合 UniApp 示例教程 #### 后端配置:Spring Boot 配置 WebSocket 支持 为了使 Spring Boot 能够处理来自 UniApp 的连接请求,需先设置 WebSocket 功能。这可以通过引入必要的依赖项并编写相应的配置类来完成。 在 `pom.xml` 文件中加入 WebSocket 及其他所需的支持库: ```xml <dependencies> <!-- WebSocket support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- Other dependencies... --> </dependencies> ``` 创建个名为 `WebSocketConfig.java` 的 Java 类用于定义 WebSocket 连接的行为模式[^1]: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").withSockJS(); } } ``` 此段代码启用了简单的消息代理,并指定了应用程序的目的地前缀以及 STOMP 终结点的位置。 #### 前端开发:UniApp 中建立 WebSocket 客户端 对于前端部分,在新建好的 UniApp 工程里通过调用原生 API 或者借助第三方插件实现与服务器之间的通信逻辑。 编辑页面组件中的 JavaScript 方法以初始化 Web Socket 实例并与后台保持实时互动: ```javascript export default { data() { return { socketTask: null, isConnected: false, }; }, onLoad() { this.initSocketConnection(); }, methods: { initSocketConnection() { const url = 'wss://yourserver.com/ws'; uni.connectSocket({ url: url, success(res) { console.log('Connected to server:', res); }, fail(err) { console.error('Failed connecting to server:', err); } }); uni.onSocketOpen((res) => { this.isConnected = true; console.log('WebSocket connection opened', res); }); // Handle incoming messages from the backend... } // More functions here... } }; ``` 上述脚本展示了怎样利用 `uni.connectSocket()` 函数发起对指定 URL 地址的服务端口的链接尝试;旦成功,则会触发回调函数执行进步的操作,比如发送验证信息给对方确认身份合法性等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@穷且益坚,不坠青云之志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值