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

文章介绍了如何在Postmanv8.5及以上版本中使用WebSocket进行服务器端编程,展示了`WebSocketServer`类的实现,包括连接、断开、消息传递以及群发功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 

### 如何使用 Postman 测试 WebSocket 连接 #### 工具准备 为了测试 WebSocket 接口,Postman 自 v8.5.1 版本起支持 WebSocket 功能。如果当前使用的 Postman 版本较低,则需要升级到指定版本或更高版本[^3]。 #### 配置步骤说明 以下是配置和测试 WebSocket 连接的具体方法: 1. **启动 Postman 并打开 WebSocket 模块** 在 Postman 中切换至左侧菜单栏中的 “WebSocket” 选项卡。如果没有看到该模块,请确认已安装最新版 Postman 或启用实验功能[^2]。 2. **输入目标 URL** 在 WebSocket 输入框中填写完整的 WebSocket 地址(通常以 `ws://` 或 `wss://` 开头)。例如: ```plaintext ws://echo.websocket.org ``` 3. **建立连接** 单击“Connect”按钮发起连接请求。一旦成功建立连接,状态会显示为绿色并提示“Connected”。此时可以发送消息给服务器[^1]。 4. **发送数据包** 使用下方的消息编辑器编写要传递的内容,点击“Send”即可向服务端推送信息。对于 JSON 数据格式的情况,记得按照标准结构化书写。 5. **接收响应** 当服务器返回应答时,这些内容会被实时展示于界面右侧区域。注意观察是否有预期的结果反馈回来。 6. **断开链接** 完成交互之后可以选择主动关闭 session ,只需按下红色标注的 Disconnect 键来终止此次通信过程。 #### 示例代码片段 下面给出一段 JavaScript 实现的一个简易 HTML 页面用于演示基本原理: ```javascript const socket = new WebSocket('ws://example.com/socket'); socket.onopen = () => { console.log('Connection established.'); }; socket.onmessage = (event) => { console.log(`Message from server: ${event.data}`); }; socket.onerror = (error) => { console.error(`Error occurred: ${error.message}`); }; socket.onclose = () => { console.warn('Connection closed.'); }; ``` 此脚本展示了如何创建一个新的 WebSocket 对象实例以及定义各种事件处理程序函数。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

stjl.xyz

谢谢打赏,祝老板心想事成

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

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

打赏作者

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

抵扣说明:

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

余额充值