阅读目录
TCP
TCP_SERVER.php
- TCP
-
- TCP_SERVER.php
- TCP_CUSTOMER.php
- UDP
-
- UDP_SERVER.php
- UDP_CLIENT.php
- HTTP
-
- 指定访问html目录,
private $server = null; public function __construct(){ //创建Server对象,监听 127.0.0.1:9501 端口 $this->server = new Swoole\Server('127.0.0.1', 8818); $this->server->set([ 'worker_num' => 4, // worker process num 'max_request' => 50, ]); //监听连接进入事件 $this->server->on('Connect', [$this, "onConnect"]); //监听数据接收事件 $this->server->on('Receive', [$this, "onReceive"]); //监听连接关闭事件 $this->server->on('Close', [$this, "onClose"]); //启动服务器 $this->server->start(); } public function onConnect($server, $fd){ echo "客户端id:{$fd}.\n"; } public function onReceive($server, $fd, $reactor_id, $data){ $server->send($fd, "发送数据: {$data}"); } public function onClose($server, $fd){ echo "客户端id: {$fd}关闭.\n"; } } new TCP();TCP_CUSTOMER.php
$client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 8818, 0.5)) { echo "connect failed. Error: {$client->errCode}\n"; } fwrite(STDOUT, "请输入:"); $res = fgets(STDIN); $client->send($res); echo $client->recv(); $client->close(); }); $scheduler->start();
private $server = null; public function __construct(){ //创建Server对象,监听 127.0.0.1:9501 端口 $this->server = new Swoole\Server('127.0.0.1', 8818, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); $this->server->set([ 'worker_num' => 4, // worker process num 'max_request' => 50, ]); //监听连接进入事件 $this->server->on('Packet', [$this, "onPacket"]); //启动服务器 $this->server->start(); } public function onPacket($server, $data, $clientInfo){ $server->sendto($clientInfo['address'], $clientInfo['port'], "Server:{$data}"); var_dump($clientInfo); } } new UDP();UDP_CLIENT.php
$client = new Swoole\Coroutine\Client(SWOOLE_SOCK_UDP); if (!$client->connect('127.0.0.1', 8818, 0.5)) { echo "connect failed. Error: {$client->errCode}\n"; } fwrite(STDOUT, "请输入:"); $res = fgets(STDIN); $client->send($res); echo $client->recv(); $client->close(); }); $scheduler->start();
HTTP.php
private $http = null; public function __construct(){ $this->http = new Swoole\Http\Server('0.0.0.0', 9501); //配置访问目录 //$this->http->set([ // 'enable_static_handler' => true, // 'document_root' => '/www/wwwroot/swoole_test/static', //]); $this->http->on('Request', [$this, 'onRequest']); $this->http->start(); } public function onRequest($request, $response){ var_dump($request->get, $request->post); $response->header('Content-Type', 'text/html; charset=utf-8'); $response->end(' Hello Swoole. #' . json_encode($request->get) . ' '); } } new HTTP();
运行
还可以带一些参数
(1) 开启前端代码的配置信息
$this->http->set([ 'enable_static_handler' => true, 'document_root' => '/www/wwwroot/swoole_test/static', ]);
(2) 新增static/index.html文件,随便写点什么
<h1>hello</h1>
(3) 访问ip:9501/index.html