[UDP 服務(wù)器]
udp_server.php
//創(chuàng)建Server對象,監(jiān)聽 127.0.0.1:9502端口,類型為SWOOLE_SOCK_UDP
$serv = new Swoole\Server("127.0.0.1", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
//監(jiān)聽數(shù)據(jù)接收事件
$serv->on('Packet', function ($serv, $data, $clientInfo) {
$serv->sendto($clientInfo['address'], $clientInfo['port'], "Server ".$data);
var_dump($clientInfo);
});
//啟動服務(wù)器
$serv->start();
UDP 服務(wù)器與 TCP 服務(wù)器不同,UDP 沒有連接的概念。啟動 Server 后,客戶端無需 Connect,直接可以向 Server 監(jiān)聽的 9502 端口發(fā)送數(shù)據(jù)包。對應(yīng)的事件為 onPacket。
- $clientInfo 是客戶端的相關(guān)信息,是一個數(shù)組,有客戶端的 IP 和端口等內(nèi)容
- 調(diào)用
$server->sendto方法向客戶端發(fā)送數(shù)據(jù)
php udp_server.php
UDP 服務(wù)器可以使用 netcat -u 來連接測試
netcat -u 127.0.0.1 9502
hello
Server: hello
在這里要注意,如果使用的是mac 筆記本 ,則為
nc -u 127.0.0.1 9502
hello
Server: hello
[HTTP 服務(wù)器]
http_server.php
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
var_dump($request->get, $request->post);
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
Http 服務(wù)器只需要關(guān)注請求響應(yīng)即可,所以只需要監(jiān)聽一個 onRequest 事件。當(dāng)有新的 Http 請求進入就會觸發(fā)此事件。事件回調(diào)函數(shù)有 2 個參數(shù),一個是 $request 對象,包含了請求的相關(guān)信息,如 GET/POST 請求的數(shù)據(jù)。
另外一個是 response 對象,對 request 的響應(yīng)可以通過操作 response 對象來完成。$response->end() 方法表示輸出一段 HTML 內(nèi)容,并結(jié)束此請求。
-
0.0.0.0表示監(jiān)聽所有IP地址,一臺服務(wù)器可能同時有多個IP,如127.0.0.1本地回環(huán) IP、192.168.1.100局域網(wǎng) IP、210.127.20.2外網(wǎng) IP,這里也可以單獨指定監(jiān)聽一個 IP -
9501監(jiān)聽的端口,如果被占用程序會拋出致命錯誤,中斷執(zhí)行。
php http_server.php
- 可以打開瀏覽器,訪問
http://127.0.0.1:9501查看程序的結(jié)果。 - 也可以使用 Apache
ab工具對服務(wù)器進行壓力測試
使用 Chrome 瀏覽器訪問服務(wù)器,會產(chǎn)生額外的一次請求,/favicon.ico,可以在代碼中響應(yīng) 404 錯誤。
$http->on('request', function ($request, $response) {
if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
$response->end();
return;
}
var_dump($request->get, $request->post);
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
應(yīng)用程序可以根據(jù) $request->server['request_uri'] 實現(xiàn)路由。如:http://127.0.0.1:9501/test/index/?a=1,代碼中可以這樣實現(xiàn) URL 路由。
$http->on('request', function ($request, $response) {
list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
//根據(jù) $controller, $action 映射到不同的控制器類和方法
(new $controller)->$action($request, $response);
});