springBoot集成webSocket并使用postMan进行测试

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

简单描述

简单来讲webSocket是一种在http协议基础上的另一种新协议叫ws协议。

http协议是单工通信客户端发起请求服务端收到请求并处理返回给客户端然后客户端收到服务端的请求。

ws协议是全双工通信客户端发起请求后相当于搭建了一个通道在不断开的情况下在这期间服务端可以把请求发给客户端客户端也可以在这期间处理别的事情不必等待服务端的响应。

webSockt实现

此次webSocket实现不包含前端代码将使用postMan来实现前端的功能。

依赖

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

配置类

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

webSocketServer

package com.czf.study.wevSocket;

import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zfChen
 * @create 2022/11/14 15:11
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    /**静态变量用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全集合也可以map改成set用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;

        if(!webSocketMap.containsKey(userId)){
            //加入集合中
            webSocketMap.put(userId,this);
            //在线数加1
            addOnlineCount();
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从集合中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+"报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}


服务端发请求接口

外面创建一个接口模拟服务端发请求给客户端

@RestController
public class DemoController {

    @RequestMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
        WebSocketServer.sendInfo(message,toUserId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }
}

测试

使用postMan创建webSocket请求

输入webSocket的地址1表示userId=1

此时控制台输出

2022-11-15 11:51:43.009  INFO 28972 --- [nio-8787-exec-5] com.czf.study.wevSocket.WebSocketServer  : 用户连接:1,当前在线人数为:1

接下来模拟服务端给客户端发送请求建立一个http请求

控制台输出

2022-11-15 11:53:48.235  INFO 28972 --- [nio-8787-exec-4] com.czf.study.wevSocket.WebSocketServer  : 发送消息到:1报文:hello

客户端收到请求

双人聊天室

webSocket经常被用作聊天室两个客户端通过一个服务端分发请求进行沟通。

在此案例中通过/来区分前一个是消息后一个是发送的对象。

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
        String[] split = message.split("/");
        try {
            sendInfo(split[0],split[1]);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

比如

2号用户收到1号发送的消息

同样的2号也可以发送消息给1号。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring