WebSocket协议相关的测试命令工具使用简介

本文涉及的产品
应用型负载均衡 ALB,每月750个小时 15LCU
公网NAT网关,每月750个小时 15CU
网络型负载均衡 NLB,每月750个小时 15LCU
简介: 本文介绍了针对WebSocket的测试工具wscat和websocat的基本使用方法,以及通过curl命令测试HTTP/HTTPS协议的方式。对于WebSocket,直接使用curl测试较为复杂,推荐使用wscat或websocat。文中详细说明了这两种工具的安装步骤、常用参数及连接示例,例如在ECS上开启8080端口监听并进行消息收发测试。此外,还提供了curl命令的手动设置头部信息以模拟WebSocket握手的示例,但指出curl仅能作为客户端测试工具,无法模拟服务器。

对于HTTP、HTTPS,可以使用curl命令来测试。

对于 WebSocket 使用curl测试过于繁琐,这里推荐可以使用 wscat 或 websocat 命令行工具,下面对基础命令使用进行讲解。

注意:下面的安装命令都是以CentOS系列的系统测试的,其他系统请使用对应的命令。

一、wscat命令

1、工具安装

wscat 是一个基于 Node.js 的工具,可以用npm工具安装。

#【可选】启用EPEL仓库,含有一些默认仓库没有的额外软件包

sudo yum install epel-release

#NodeJS包管理和分发工具

sudo yum install nodejs npm

#安装wscatt命令

sudo npm install -g wscat

2、命令参数

命令参数解释:

root@test ~]# wscat --help
Usage: wscat [options] (--listen <port> | --connect <url>)
Options:
  -V, --version                       output the version number
  --auth <username:password>          add basic HTTP authentication header
  --ca <ca>                           specify a Certificate Authority (--connect only)
  --cert <cert>                       specify a Client SSL Certificate (--connect only)
  --host <host>                       optional host
  --key <key>                         specify a Client SSL Certificate's key (--connect only)
  --max-redirects [num]               maximum number of redirects allowed (default: 10)
  --no-color                          run without color
  --passphrase [passphrase]           specify a Client SSL Certificate Key's passphrase (--connect only). If you don't provide a value, it will be prompted for
  --proxy <[protocol://]host[:port]>  connect via a proxy. Proxy must support CONNECT method
  --slash                             enable slash commands for control frames (/ping [data], /pong [data], /close [code [, reason]]) (--connect only)
  -c, --connect <url>                 connect to a WebSocket server
  -H, --header <header:value>         set an HTTP header. Repeat to set multiple (--connect only) (default: [])
  -l, --listen <port>                 listen on port
  -L, --location                      follow redirects
  -n, --no-check                      do not check for unauthorized certificates (--connect only)
  -o, --origin <origin>               optional origin
  -p, --protocol <version>            optional protocol version
  -P, --show-ping-pong                print a notification when a ping or pong is received (--connect only)
  -s, --subprotocol <protocol>        optional subprotocol. Repeat to specify more than one (default: [])
  -w, --wait <seconds>                wait given seconds after executing command (-1 to hold open)
  -x, --execute <command>             execute command after connecting. Repeat to execute more than one (--connect only) (default: [])
  -h, --help                          display help for command

常用:

--connect, -c:连接到指定的 WebSocket URL。
示例:wscat -c ws://example.com/socket
--listen, -l:作为 WebSocket 服务器监听指定的端口或地址。
示例:wscat -l 8080
--protocol <protocol>:需要指定WebSocket子协议时使用。 
示例:wscat -c ws://example.com/socket --protocol chat
--origin <origin>:设置请求头中的 Origin 字段值。 
示例:wscat -c ws://example.com/socket --origin http://example.com
--header <key:value>:添加额外的 HTTP 头信息,可以多次使用以添加多个头部。
 示例:wscat -c ws://example.com/socket --header "Authorization: Bearer token"
--no-color:禁用输出的颜色编码。
--version:显示 wscat 的版本号。
--help:显示帮助信息。

连接示例:

ECS开启8080监听:

wscat -l 8080

image.png

新窗口连接:

wscat -c ws://localhost:8080

image.png

此时服务器侧可以看到发的消息,服务器也可以发送消息:

image.png


二、websocat命令

websocat 一个功能强大的命令行工具,适用于多种平台,支持更多的连接选项和模式。可以通过编译源代码或从某些包管理器安装(例如在 Ubuntu 上可以通过 sudo apt-get install websocat 安装)。

1、工具安装

文件链接:

https://github.com/vi/websocat/releases

下载对应版本的文件:
wget https://github.com/vi/websocat/releases/download/v1.14.0/websocat.x86_64-unknown-linux-musl
添加可执行的权限:
chmod +x websocat.x86_64-unknown-linux-musl
移动到 /usr/local/bin/:
sudo mv websocat.x86_64-unknown-linux-musl /usr/local/bin/websocat
完成上述步骤后,可以在终端中输入 websocat --version 来检查是否安装成功以及查看其版本号。
[root@test]$ websocat --version 
websocat 1.14.0

2、命令参数

命令参数解释:

[root@test]]$ websocat --help
websocat 1.14.0
Vitaly "_Vi" Shukela <vi0oss@gmail.com>
Command-line client for web sockets, like netcat/curl/socat for ws://.
USAGE:
    websocat ws://URL | wss://URL               (simple client)
    websocat -s port                            (simple server)
    websocat [FLAGS] [OPTIONS] <addr1> <addr2>  (advanced mode)
FLAGS:
    (some flags are hidden, see --help=long)
    -e, --set-environment
            Set WEBSOCAT_* environment variables when doing exec:/cmd:/sh-c:
            Currently it's WEBSOCAT_URI and WEBSOCAT_CLIENT for
            request URI and client address (if TCP)
            Beware of ShellShock or similar security problems.
    -E, --exit-on-eof                            Close a data transfer direction if the other one reached EOF
        --jsonrpc
            Format messages you type as JSON RPC 2.0 method calls. First word becomes method name, the rest becomes
            parameters, possibly automatically wrapped in [].
    -0, --null-terminated                        Use \0 instead of \n for linemode
            --no-fixups to discover what is being inserted automatically and read the full manual about Websocat
            internal workings.
    -1, --one-message                            Send and/or receive only one message. Use with --no-close and/or -u/-U.
        --oneshot                                Serve only once. Not to be confused with -1 (--one-message)
        --print-ping-rtts
            Print measured round-trip-time to stderr after each received WebSocket pong.
    -q                                           Suppress all diagnostic messages, except of startup errors
    -s, --server-mode                            Simple server mode: specify TCP port or addr:port as single argument
    -S, --strict
            strict line/message mode: drop too long messages instead of splitting them, drop incomplete lines.
    -k, --insecure                               Accept invalid certificates and hostnames while connecting to TLS
    -u, --unidirectional                         Inhibit copying data in one direction
    -U, --unidirectional-reverse
            Inhibit copying data in the other direction (or maybe in both directions if combined with -u)
    -v                                           Increase verbosity level to info or further
    -b, --binary                                 Send message to WebSockets as binary messages
    -n, --no-close                               Don't send Close message to websocket on EOF
    -t, --text                                   Send message to WebSockets as text messages
        --base64
            Encode incoming binary WebSocket messages in one-line Base64 If `--binary-prefix` (see `--help=full`) is
            set, outgoing WebSocket messages that start with the prefix are decoded from base64 prior to sending.
OPTIONS:
    (some options are hidden, see --help=long)
        --socks5 <auto_socks5>
            Use specified address:port as a SOCKS5 proxy. Example: --socks5 127.0.0.1:9050
        --basic-auth <basic_auth>
            Add `Authorization: Basic` HTTP request header with this base64-encoded parameter. Also available as
            `WEBSOCAT_BASIC_AUTH` environment variable
        --basic-auth-file <basic_auth_file>
            Add `Authorization: Basic` HTTP request header base64-encoded content of the specified file
    -B, --buffer-size <buffer_size>                                  Maximum message size, in bytes [default: 65536]
        --close-reason <close_reason>
            Close connection with a reason message. This option only takes effect if --close-status-code option is
            provided as well.
        --close-status-code <close_status_code>                      Close connection with a status code.
    -H, --header <custom_headers>...
            Add custom HTTP header to websocket client request. Separate header name and value with a colon and
            optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
            arguments, leading to confusing errors. Specify headers at the end or with equal sign like -H='X: y'.
        --server-header <custom_reply_headers>...
            Add custom HTTP header to websocket upgrade reply. Separate header name and value with a colon and
            optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
            arguments, leading to confusing errors.
        --header-to-env <headers_to_env>...
            Forward specified incoming request header to H_* environment variable for `exec:`-like specifiers.
    -h, --help <help>
            See the help.
            --help=short is the list of easy options and address types
            --help=long lists all options and types (see [A] markers)
            --help=doc also shows longer description and examples.
        --max-messages <max_messages>
            Maximum number of messages to copy in one direction.
        --max-messages-rev <max_messages_rev>
            Maximum number of messages to copy in the other direction.
        --conncap <max_parallel_conns>
            Maximum number of simultaneous connections for listening mode
        --origin <origin>                                            Add Origin HTTP header to websocket client request
        --pkcs12-der <pkcs12_der>
            Pkcs12 archive needed to accept SSL connections, certificate and key.
            A command to output it: openssl pkcs12 -export -out output.pkcs12 -inkey key.pem -in cert.pem
            Use with -s (--server-mode) option or with manually specified TLS overlays.
            See moreexamples.md for more info.
        --pkcs12-passwd <pkcs12_passwd>
            Password for --pkcs12-der pkcs12 archive. Required on Mac.
    -p, --preamble <preamble>...
            Prepend copied data with a specified string. Can be specified multiple times.
    -P, --preamble-reverse <preamble_reverse>...
            Prepend copied data with a specified string (reverse direction). Can be specified multiple times.
        --restrict-uri <restrict_uri>
            When serving a websocket, only accept the given URI, like `/ws`
            This liberates other URIs for things like serving static files or proxying.
    -F, --static-file <serve_static_files>...
            Serve a named static file for non-websocket connections.
            Argument syntax: <URI>:<Content-Type>:<file-path>
            Argument example: /index.html:text/html:index.html
            Directories are not and will not be supported for security reasons.
            Can be specified multiple times. Recommended to specify them at the end or with equal sign like `-F=...`,
            otherwise this option may eat positional arguments
        --ua <useragent>
            Set `User-Agent` request header to this value. Similar to setting it with `-H`.
        --protocol <websocket_protocol>
            Specify this Sec-WebSocket-Protocol: header when connecting
        --server-protocol <websocket_reply_protocol>
            Force this Sec-WebSocket-Protocol: header when accepting a connection
        --websocket-version <websocket_version>                      Override the Sec-WebSocket-Version value
        --ping-interval <ws_ping_interval>                           Send WebSocket pings each this number of seconds
        --ping-timeout <ws_ping_timeout>
            Drop WebSocket connection if Pong message not received for this number of seconds
ARGS:
    <addr1>    In simple mode, WebSocket URL to connect. In advanced mode first address (there are many kinds of
               addresses) to use. See --help=types for info about address types. If this is an address for
               listening, it will try serving multiple connections.
    <addr2>    In advanced mode, second address to connect. If this is an address for listening, it will accept only
               one connection.
Basic examples:
  Command-line websocket client:
    websocat ws://ws.vi-server.org/mirror/
    
  WebSocket server
    websocat -s 8080
    
  WebSocket-to-TCP proxy:
    websocat --binary ws-l:127.0.0.1:8080 tcp:127.0.0.1:5678
    
Partial list of address types:
        ws://                   Insecure (ws://) WebSocket client. Argument is host and URL.
        wss://                  Secure (wss://) WebSocket client. Argument is host and URL.
        ws-listen:              WebSocket server. Argument is host and port to listen.
        wss-listen:             Listen for secure WebSocket connections on a TCP port
        tcp:                    Connect to specified TCP host and port. Argument is a socket address.
        tcp-listen:             Listen TCP port on specified address.
        ssl-listen:             Listen for SSL connections on a TCP port
        sh-c:                   Start specified command line using `sh -c` (even on Windows)
        cmd:                    Start specified command line using `sh -c` or `cmd /C` (depending on platform)
        readfile:               Synchronously read a file. Argument is a file path.
        writefile:              Synchronously truncate and write a file.
        appendfile:             Synchronously append a file.
        udp:                    Send and receive packets to specified UDP socket, from random UDP port  
        udp-listen:             Bind an UDP socket to specified host:port, receive packet
        -                       Read input from console, print to console. Uses threaded implementation even on UNIX unless requested by `--async-stdio` CLI option.
        mirror:                 Simply copy output to input. No arguments needed.
        literalreply:           Reply with a specified string for each input packet.
        literal:                Output a string, discard input.
        random:                 Generate random bytes when being read from, discard written bytes.
Partial list of overlays:
        broadcast:              Reuse this connection for serving multiple clients, sending replies to all clients.
        autoreconnect:          Re-establish underlying connection on any error or EOF
        foreachmsg:             Execute something for each incoming message.
        log:                    Log each buffer as it pass though the underlying connector.
See more address types with the --help=long option.
See short examples and --dump-spec names for most address types and overlays with --help=doc option

常用:

基本连接:
-b 或 --binary: 以二进制模式运行,而不是文本模式。
-t 或 --text: 强制使用文本模式(默认)。
连接类型:
ws://... 或 wss://...: 指定要连接的WebSocket URL。
tcp-listen:: 监听TCP端口,等待传入连接并将其转换为WebSocket连接。
unix-l:: 类似于tcp-listen,但使用Unix域套接字。
双向通信:
可以通过指定两个方向(如 websocat ws://example.com/ws tcp-listen:1234)来进行不同协议间的转发。
其他常用选项:
-H <header> 或 --header <header>: 添加HTTP头到客户端握手请求中。
-E 或 --ping-interval <seconds>: 设置发送PING帧的时间间隔,维持连接活跃。
-v 或 --verbose: 提供详细输出,便于调试。
-q 或 --quiet: 减少输出信息,仅显示错误信息。
-V 或 --version: 显示版本信息并退出。
安全相关:
使用 wss:// 来指示应使用加密的WebSocket连接。
--ca-file <path>: 指定CA证书文件路径,用于验证服务器证书。
--insecure: 跳过SSL/TLS证书验证(不推荐在生产环境中使用)。


连接示例:

ECS开启8080监听:

websocat -s 8080

新窗口连接:

websocat ws://localhost:8080 -v

此时,客户端服务器可以收发信息:

image.png

三、curl命令

curl命令不能直接使用,需要-H手动添加参数,直接请求是http[s]的形式。

curl  -H 'Upgrade: websocket' -H 'Connection: Upgrade' -H 'Sec-WebSocket-Version: 13' -H 'Sec-webSocket-Key: xxxxxxxxx' -ws 'http://localhost:8080/socket.io/?EIO=4&transport=websocket'


实际即是参考报文格式进行填充:

image.png

curl命令只能模拟客户端,不能模拟服务器测试。

目录
打赏
0
4
4
1
1
分享
相关文章
UAT测试排程工具深度解析:让验收测试不再失控,项目稳稳上线
在系统交付节奏加快的背景下,“测试节奏混乱”已成为项目延期的主因之一。UAT测试排程工具应运而生,帮助团队结构化拆解任务、清晰分配责任、实时掌控进度,打通需求、测试、开发三方协作闭环,提升测试效率与质量。本文还盘点了2025年热门UAT工具,助力团队选型落地,告别靠表格和群聊推进测试的低效方式,实现有节奏、有章法的测试管理。
DevOps看板工具中的协作功能:如何打破开发、测试与运维之间的沟通壁垒
在DevOps实践中,看板工具通过可视化任务管理和自动化流程,提升开发与运维团队的协作效率。它支持敏捷开发、持续交付,助力团队高效应对需求变化,实现跨职能协作与流程优化。
Go 语言测试与调试:`go test` 工具用法
`go test` 是 Go 语言内置的测试工具,支持单元测试、基准测试、示例测试等功能。本文详解其常用参数、调试技巧及性能测试命令,并提供实际项目中的应用示例与最佳实践。
Go语言测试简明指南:深度解读go test命令
总的来说,go test是 Go 语言中一个强而有力的工具,每个 Go 程序员都应该掌握并把它融入到日常的开发和调试过程中。就像是一个眼镜过滤出的太阳,让我们在宽阔的代码海洋中游泳,而不是淹没。用好它,让我们的代码更健壮,让我们的生产力更强效。
174 23
Jmeter工具使用:HTTP接口性能测试实战
希望这篇文章能够帮助你初步理解如何使用JMeter进行HTTP接口性能测试,有兴趣的话,你可以研究更多关于JMeter的内容。记住,只有理解并掌握了这些工具,你才能充分利用它们发挥其应有的价值。+
509 23
全平台开源即时通讯IM框架MobileIMSDK:7端+TCP/UDP/WebSocket协议,鸿蒙NEXT端已发布,5.7K Stars
全平台开源即时通讯IM框架MobileIMSDK:7端+TCP/UDP/WebSocket协议,鸿蒙NEXT端已发布,5.7K Stars
235 1
接口测试新选择:Postman替代方案全解析
在软件开发中,接口测试工具至关重要。Postman长期占据主导地位,但随着国产工具的崛起,越来越多开发者转向更适合中国市场的替代方案——Apifox。它不仅支持中英文切换、完全免费不限人数,还具备强大的可视化操作、自动生成文档和API调试功能,极大简化了开发流程。
2025接口测试全攻略:高并发、安全防护与六大工具实战指南
本文探讨高并发稳定性验证、安全防护实战及六大工具(Postman、RunnerGo、Apipost、JMeter、SoapUI、Fiddler)选型指南,助力构建未来接口测试体系。接口测试旨在验证数据传输、参数合法性、错误处理能力及性能安全性,其重要性体现在早期发现问题、保障系统稳定和支撑持续集成。常用方法包括功能、性能、安全性及兼容性测试,典型场景涵盖前后端分离开发、第三方服务集成与数据一致性检查。选择合适的工具需综合考虑需求与团队协作等因素。
447 24
除了postman还有什么接口测试工具
最好还是使用国内的接口测试软件,其实国内替换postman的软件有很多,这里我推荐使用yunedit-post这款接口测试工具来代替postman,因为它除了接口测试功能外,在动态参数的支持、后置处理执行sql语句等支持方面做得比较好。而且还有接口分享功能,可以生成接口文档给团队在线浏览。
190 2
Socket.IO介绍,以及怎么连接测试Socket.IO接口?
Socket.IO 是一个用于浏览器和服务器间实时双向通信的库,支持低延迟消息传递、跨平台运行及自动重连。文章介绍了其特点与调试需求,并详细说明如何使用 Apifox 工具创建、连接、发送/接收 Socket.IO 事件,以及团队协作和调试技巧。掌握这些技能可提升实时应用开发效率与质量。

热门文章

最新文章

AI助理
登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问

你好,我是AI助理

可以解答问题、推荐解决方案等