Linux
环境下,分别使用curl
和wscat
命令测试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
$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"; });
$web_socket->on('open', function ($web_socket, $request) { var_dump($request->fd, "Hello, Welcome client-{$fd}\n"); });
$web_socket->on('message', function ($web_socket, $frame) { echo "received message: {$frame->data}\n"; $web_socket->push($frame->fd, "server: {$frame->data}"); });
$web_socket->on('close', function ($web_socket, $fd) { echo "client-{$fd} is closed\n"; });
$web_socket->start();
|
1 2
| [root@caoxl Start] WebSocket server is started at http:
|
wscat
wscat是一个用来连接websocket的命令行工具,nodejs开发的。
1 2 3 4 5 6 7 8
| [root@caoxl Start] /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] 3.0.0
|
1 2 3
| > [root@caoxl Start] 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:
|
注意这里不需要特定的密钥(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
|