78 lines
2.1 KiB
PHP
78 lines
2.1 KiB
PHP
![]() |
<?php
|
|||
|
/**
|
|||
|
* TCP服务端类
|
|||
|
* User: fantasticbin
|
|||
|
* Date: 2020/1/15
|
|||
|
*/
|
|||
|
class Tcp
|
|||
|
{
|
|||
|
const HOST = '127.0.0.1';
|
|||
|
const PORT = 9502;
|
|||
|
const WORKER_NUM = 2;
|
|||
|
const MAX_REQUEST = 10000;
|
|||
|
|
|||
|
public $server = null;
|
|||
|
|
|||
|
public function __construct()
|
|||
|
{
|
|||
|
// 创建TCP服务器,第四个参数默认指定为TCP,监听 127.0.0.1:9501 端口
|
|||
|
$this->server = new Swoole\Server(self::HOST, self::PORT);
|
|||
|
|
|||
|
// 设置TCP服务器参数
|
|||
|
$this->server->set([
|
|||
|
'worker_num' => self::WORKER_NUM,
|
|||
|
'max_request' => self::MAX_REQUEST
|
|||
|
]);
|
|||
|
|
|||
|
// 监听连接进入事件
|
|||
|
$this->server->on('Connect', [$this, 'onConnect']);
|
|||
|
// 监听数据接收事件
|
|||
|
$this->server->on('Receive', [$this, 'onReceive']);
|
|||
|
// 监听连接关闭事件
|
|||
|
$this->server->on('Close', [$this, 'onClose']);
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 监听连接进入事件
|
|||
|
* @param $serv Swoole\Server TCP对象
|
|||
|
* @param $client_id int 客户端连接ID
|
|||
|
* @param $reactor_id int 线程ID
|
|||
|
*/
|
|||
|
public function onConnect($serv, $client_id, $reactor_id)
|
|||
|
{
|
|||
|
echo 'Client: Connect.' . PHP_EOL . 'This client id: ' . $client_id . PHP_EOL . 'This reactor id: ' . $reactor_id . PHP_EOL;
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 监听数据接收事件
|
|||
|
* @param $serv Swoole\Server TCP对象
|
|||
|
* @param $client_id int 客户端连接ID
|
|||
|
* @param $reactor_id int 线程ID
|
|||
|
* @param $data string 客户端传入的字符串
|
|||
|
*/
|
|||
|
public function onReceive($serv, $client_id, $reactor_id, $data)
|
|||
|
{
|
|||
|
$serv->send($client_id, 'This client id: ' . $client_id . PHP_EOL . 'This reactor id: ' . $reactor_id . PHP_EOL . 'Hello ' . $data . '!' . PHP_EOL);
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 监听连接关闭事件
|
|||
|
* @param $serv Swoole\Server TCP对象
|
|||
|
* @param $client_id int 客户端连接ID
|
|||
|
*/
|
|||
|
public function onClose($serv, $client_id)
|
|||
|
{
|
|||
|
echo 'Client: Client ' . $client_id . ' close.' . PHP_EOL;
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 启动TCP服务器
|
|||
|
*/
|
|||
|
public function start()
|
|||
|
{
|
|||
|
$this->server->start();
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
$tcp = new Tcp();
|
|||
|
$tcp->start();
|