内容
活动
关注

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

简介: 本文介绍了针对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命令只能模拟客户端,不能模拟服务器测试。

相关文章
|
1月前
|
监控 负载均衡 安全
WebSocket网络编程深度实践:从协议原理到生产级应用
蒋星熠Jaxonic,技术宇宙中的星际旅人,以代码为舟、算法为帆,探索实时通信的无限可能。本文深入解析WebSocket协议原理、工程实践与架构设计,涵盖握手机制、心跳保活、集群部署、安全防护等核心内容,结合代码示例与架构图,助你构建稳定高效的实时应用,在二进制星河中谱写极客诗篇。
WebSocket网络编程深度实践:从协议原理到生产级应用
|
2月前
|
机器学习/深度学习 人工智能 测试技术
EdgeMark:嵌入式人工智能工具的自动化与基准测试系统——论文阅读
EdgeMark是一个面向嵌入式AI的自动化部署与基准测试系统,支持TensorFlow Lite Micro、Edge Impulse等主流工具,通过模块化架构实现模型生成、优化、转换与部署全流程自动化,并提供跨平台性能对比,助力开发者在资源受限设备上高效选择与部署AI模型。
310 9
EdgeMark:嵌入式人工智能工具的自动化与基准测试系统——论文阅读
|
2月前
|
Java 测试技术 API
自动化测试工具集成及实践
自动化测试用例的覆盖度及关键点最佳实践、自动化测试工具、集成方法、自动化脚本编写等(兼容多语言(Java、Python、Go、C++、C#等)、多框架(Spring、React、Vue等))
132 6
|
3月前
|
前端开发 Java jenkins
Jmeter压力测试工具全面教程和使用技巧。
JMeter是一个能够模拟高并发请求以检查应用程序各方面性能的工具,包括但不限于前端页面、后端服务及数据库系统。熟练使用JMeter不仅能够帮助发现性能瓶颈,还能在软件开发早期就预测系统在面对真实用户压力时的表现,确保软件质量和用户体验。在上述介绍的基础上,建议读者结合官方文档和社区最佳实践,持续深入学习和应用。
815 10
|
3月前
|
监控 Java 数据挖掘
利用Jmeter工具进行HTTP接口的性能测试操作
基础上述步骤反复迭代调整直至满足预期目标达成满意水平结束本轮压力评估周期进入常态监控阶段持续关注系统运转状态及时发现处理新出现问题保障服务稳定高效运作
499 0
|
4月前
|
敏捷开发 运维 数据可视化
DevOps看板工具中的协作功能:如何打破开发、测试与运维之间的沟通壁垒
在DevOps实践中,看板工具通过可视化任务管理和自动化流程,提升开发与运维团队的协作效率。它支持敏捷开发、持续交付,助力团队高效应对需求变化,实现跨职能协作与流程优化。
|
5月前
|
测试技术 程序员 Go
Go语言测试简明指南:深度解读go test命令
总的来说,go test是 Go 语言中一个强而有力的工具,每个 Go 程序员都应该掌握并把它融入到日常的开发和调试过程中。就像是一个眼镜过滤出的太阳,让我们在宽阔的代码海洋中游泳,而不是淹没。用好它,让我们的代码更健壮,让我们的生产力更强效。
426 23
|
5月前
|
Java 测试技术 容器
Jmeter工具使用:HTTP接口性能测试实战
希望这篇文章能够帮助你初步理解如何使用JMeter进行HTTP接口性能测试,有兴趣的话,你可以研究更多关于JMeter的内容。记住,只有理解并掌握了这些工具,你才能充分利用它们发挥其应有的价值。+
946 23
|
5月前
|
数据可视化 测试技术 Go
Go 语言测试与调试:`go test` 工具用法
`go test` 是 Go 语言内置的测试工具,支持单元测试、基准测试、示例测试等功能。本文详解其常用参数、调试技巧及性能测试命令,并提供实际项目中的应用示例与最佳实践。
|
4月前
|
人工智能 数据可视化 测试技术
UAT测试排程工具深度解析:让验收测试不再失控,项目稳稳上线
在系统交付节奏加快的背景下,“测试节奏混乱”已成为项目延期的主因之一。UAT测试排程工具应运而生,帮助团队结构化拆解任务、清晰分配责任、实时掌控进度,打通需求、测试、开发三方协作闭环,提升测试效率与质量。本文还盘点了2025年热门UAT工具,助力团队选型落地,告别靠表格和群聊推进测试的低效方式,实现有节奏、有章法的测试管理。
下一篇