对于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
新窗口连接:
wscat -c ws://localhost:8080
此时服务器侧可以看到发的消息,服务器也可以发送消息:
二、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
此时,客户端服务器可以收发信息:
三、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'
实际即是参考报文格式进行填充:
curl命令只能模拟客户端,不能模拟服务器测试。