swoole的TCP服務

1.服務器端程序代碼
tcp_server.phpphp

<?php
///建立Server對象,監聽 127.0.0.1:9501端口
$serv = new swoole_server("127.0.0.1", 9501);服務器

$serv->set([
  'worker_num' => 4, // worker 進程數,cpu的1-4倍
  'max_request'=> 10000
]);swoole

// 命令行查看server開啓的worker數
// 若是當前文件名爲 tcp_server.php, 則 ps aft | grep tcp_server.phptcp

//監聽鏈接進入事件
$serv->on('connect', function ($serv, $fd) {
  echo "Client: fd:{$fd} Connect.\n";
});操作系統

//監聽數據接收事件
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
  $serv->send($fd, "Server: fd:{$fd} data:{$data}");
});命令行

//監聽鏈接關閉事件
$serv->on('close', function ($serv, $fd) {
  echo "Client: fd:{$fd} Close.\n";
});server

//啓動服務器
$serv->start();對象

2.客戶端程序代碼
tcp_client.php進程

<?php
/**
* 建立同步阻塞模式下的TCP客戶端
* 同步阻塞模式下connect/send/recv會等待IO完成後再返回,服務端返回後纔會向下執行。
* 同步阻塞模式下並不會消耗CPU資源,IO操做未完成當前進程會自動轉入sleep模式。
* 當IO完成後操做系統會喚醒當前進程,繼續向下執行代碼。
*/
$client = new swoole_client(SWOOLE_TCP);事件

//鏈接到服務器
$host = "127.0.0.1";
$port = 9501;
$timeout = 1; //超過與服務器交互的超時秒數會自動斷開
if (!$client->connect($host, $port, $timeout)) {
  die("[connect] failed" . PHP_EOL);
}

//發送數據
$message = "hello world";
if (!$client->send($message)) {
  die("[send] failed" . PHP_EOL);
}

//接收數據
if (!$data = $client->recv()) {
  die("[recv] failed" . PHP_EOL);
}
echo $data . PHP_EOL;

//關閉鏈接
$client->close();

3.服務器端執行程序
php tcp_server.php

在命令行下運行 php tcp_server.php 程序,啓動成功後可使用 netstat -an | grep 9501 看到,已經在監聽 9501 端口。

4.客戶端執行程序
php tcp_client.php

5.服務器端執行結果
Client: fd:1 Connect.
Client: fd:1 Close.

6.客戶端執行結果Server: fd:1 data:hello world

相關文章
相關標籤/搜索