Linux 命令行测试WebSocket

Linux环境下,分别使用curlwscat命令测试websocket连接。

websocket

这里用swoole搭建一个websocket server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

// 创建WebSocket服务器对象, 监听0.0.0.0:9502
$web_socket = new swoole_websocket_server('0.0.0.0', 9502);

$web_socket->on('start', function ($web_socket) {
echo "WebSocket server is started at http://127.0.0.1:9502\n";
});

// 监听WebSocket连接打开事件
$web_socket->on('open', function ($web_socket, $request) {
var_dump($request->fd, "Hello, Welcome client-{$fd}\n");
});

// 监听WebSocket消息事件
$web_socket->on('message', function ($web_socket, $frame) {
echo "received message: {$frame->data}\n";
$web_socket->push($frame->fd, "server: {$frame->data}");
});

// 监听WebSocket连接关闭事件
$web_socket->on('close', function ($web_socket, $fd) {
echo "client-{$fd} is closed\n";
});

// 开启服务
$web_socket->start();
  • 开启websocket server
1
2
[root@caoxl Start]# php websocket_server.php 
WebSocket server is started at http://127.0.0.1:950

wscat

wscat是一个用来连接websocket的命令行工具,nodejs开发的。

1
2
3
4
5
6
7
8
[root@caoxl Start]# npm install -g wscat
/root/.nvm/versions/node/v11.1.0/bin/wscat -> /root/.nvm/versions/node/v11.1.0/lib/node_modules/wscat/bin/wscat
+ wscat@3.0.0
added 12 packages from 9 contributors in 8.03s

// 测试一下
[root@caoxl Start]# wscat -V
3.0.0
  • 使用wscat测试WebSocket
1
2
3
> [root@caoxl Start]# wscat -c ws://127.0.0.1:9502
Connected (press CTRL+C to quit)
>

curl

1
2
3
4
5
6
7
8
9
curl --include \
--no-buffer \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Host: http://127.0.0.1:9502" \
--header "Origin: http://www.caoxl.com" \
--header "Sec-WebSocket-Key: NVwjmQUcWCenfWu98asDmg==" \
--header "Sec-WebSocket-Version: 13" \
http://127.0.0.1:9502

注意这里不需要特定的密钥(Sec-WebSocket-Key),所以随便取一个都可以。该头文件的作用是防止缓存websocket请求。

  • 正常情况下输出如下:
1
2
3
4
5
6
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: oPhRcOTYgRvrC0D+cTPcN3XYC1k=
Sec-WebSocket-Version: 13
Server: swoole-http-server

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2022 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :