当前位置: 首页 > news >正文

postman连接websocket, 建立连接、聊天测试(v8.5.1)

1. postman v8.5版本 以上支持 websocket。

2. 选择websocket请求模块
File - New...

3. WebSocketServer.java 

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.CopyOnWriteArraySet;


/**
 * 访问: ws://localhost:8080/ws/{userId}
 */
@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;
    private String userId = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.userId = userId;
        sendMessage(userId + "用户" + ", 连接成功 !");

        System.out.println("【websocket】" + userId + "用户" + "已连接!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1

        System.out.println("【websocket】" + userId +  "用户" +  "已关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {

        if(message.startsWith("target-")){
            int index = message.indexOf(":");
            String userId = message.substring(7,index);
            sendInfo(message.substring(index + 1), userId);
            return;
        }

        this.session = session;
        sendMessage("【websocket】 服务端收到来自窗口" + userId + "发送的消息:" + message);

    }

    @OnError
    public void onError(Session session, Throwable error) {
        this.session = session;
        error.printStackTrace();
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 群发消息
    /**
     * 群发自定义消息
     */
    public static void sendInfo(@PathParam("userId") String userId, String message) {
        System.out.println("【websocket】 推送消息给" + userId +  "用户" + ",推送内容:" + message);

        for (WebSocketServer item : webSocketSet) {
            //这里可以设定只推送给这个userId的,为null则全部推送
            if (userId == null) {
//                    item.sendMessage(message);
            } else if (item.userId.equals(userId)) {
                item.sendMessage(message);
            }
        }
    }


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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

4. postman请求, ws:// 开头

ws://localhost:8080/ws/{userId}

⬆️ 是发送的信息,     ⬇️ 是接收到的信息

userId: 101用户连接

userId: 102用户连接

 userId: 101用户给102用户发消息

 userId: 102用户给101用户发消息

控制台输出:
2023-09-12 21:59:37.038  INFO 5172 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-09-12 21:59:37.038  INFO 5172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-09-12 21:59:37.039  INFO 5172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
【websocket】101用户已连接!当前在线人数为1
【websocket】102用户已连接!当前在线人数为2
【websocket】 推送消息到给102用户,推送内容:你好, 很高兴认识你; 我是101用户
【websocket】 推送消息到给101用户,推送内容:你好, 我也很高兴认识你; 我是102用户

postman v8.5.1版本下载
链接: https://pan.baidu.com/s/1CaXKkIFLyluLJd3KNdSlaw 
提取码: dhj5 

相关文章:

  • docker 网络模式 与 ftp 主动模式与被动模式
  • 如何获取美团的热门商品和服务
  • 数据结构与算法之Set布隆过滤器
  • Jenkins List Git Branches插件 构建选择指定git分支
  • 外包干了2个月,技术退步明显。。。。。
  • python基础语法(三)
  • 【八大经典排序算法】冒泡排序
  • 目标检测中生成锚框函数详解
  • Python爬虫:获取必应图片的下载链接
  • MySQL 解决数据重复添加
  • C语言——贪吃蛇小游戏
  • 82 # koa-bodyparser 中间件的使用以及实现
  • Java程序连接 Mysql 超时问题 - 数据包过大,导致超时,# 配置网络超时时间 socketTimeout: 1800000
  • Python3.10 IDLE更换主题
  • 对于每种情况分别统计概率来计算期望+树上连通块统计:ARC165E
  • Prometheus 监控指南:如何可靠地记录数字时间序列数据
  • Java-API简析_java.net.Inet6Address类(基于 Latest JDK)(浅析源码)
  • 华为认证 | HCIA、HCIP、HCIE,难度区别在哪里?
  • 请问一下就是业务概念模型和业务逻辑模型有啥关系
  • 【Linux】网络篇:UDP、TCP 网络接口及使用
  • 重庆市委原常委、政法委原书记陆克华严重违纪违法被开除党籍和公职
  • AI时代的阅读——当今时代呼唤文学的思想实验和人文认知
  • 证券时报:金价再创历史新高,“避险”黄金不应异化为投机工具
  • 夜读丨秦腔里的乡魂
  • 海南公布知识产权保护典型案例,一企业违规申请注册“中华”商标被处罚
  • ESG领跑者|每一步都向前,李宁要让可持续发展成为可持续之事