swoole tcp
tcp server
<?php
/**
* Class Tcp
* Tcp服務(wù)
*/
class Tcp {
CONST HOST = "0.0.0.0";
CONST PORT = 9501;
public $tcp = null;
public function __construct()
{
$this->tcp = new swoole_server(self::HOST, self::PORT);
$this->tcp->set(
[
'worker_num' => 6,
'max_request' => 10000,
]
);
$this->tcp->on('connect', [$this, 'onConnect']);
$this->tcp->on('receive', [$this, 'onReceive']);
$this->tcp->on('close', [$this, 'onClose']);
$this->tcp->start();
}
/**
* 監(jiān)聽連接事件
* @param $tcp
* @param $fd
* @param $reactor_id
*/
public function onConnect($tcp, $fd, $reactorId)
{
echo "客戶端id:{$fd}連接成功,來自于線程{$reactorId}\n";
}
/**
* 監(jiān)聽接收事件
* @param $tcp
* @param $fd
* @param $reactor_id
* @param $data
*/
public function onReceive($tcp, $fd, $reactorId, $data)
{
echo "接收到了客戶端id: {$fd} 發(fā)送的數(shù)據(jù):{$data}";
$sendData = "服務(wù)端將客戶端發(fā)送的數(shù)據(jù)原樣返回:{$data}";
$tcp->send($fd, $sendData);
}
/**
* 監(jiān)聽關(guān)閉事件
* @param $tcp
* @param $fd
*/
public function onClose($tcp, $fd)
{
echo "客戶端id: {$fd} 關(guān)閉了連接\n";
}
}
$tcp = new Tcp();
開啟服務(wù):
? server [master] ? php tcp.php
[2018-04-30 14:41:23 @69315.0] TRACE Create swoole_server host=0.0.0.0, port=9501, mode=3, type=1
使用telnet連接
? client [master] ? telnet 127.0.0.1 9501
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello swoole
服務(wù)端將客戶端發(fā)送的數(shù)據(jù)原樣返回:hello swoole
自定義 tcp client
tcp_client.php
<?php
/**
* Class TcpClient
* Tcp客戶端
*/
class TcpClient
{
const HOST = "127.0.0.1";
const PORT = 9501;
public $client = null;
public function __construct()
{
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
$this->connect();
}
public function connect()
{
if(!$this->client->connect(self::HOST, self::PORT)) {
echo '連接失敗';
exit;
}
}
public function send()
{
fwrite(STDOUT, '請輸入消息:');
$msg = trim(fgets(STDIN));
$this->client->send($msg);
}
public function receive()
{
$result = $this->client->recv();
echo $result . "\n";
}
}
$client = new TcpClient();
$client->send();
$client->receive();
執(zhí)行結(jié)果:
? client [master] ? php tcp_client.php
請輸入消息:swoole tcp 客戶端測試
服務(wù)端將客戶端發(fā)送的數(shù)據(jù)原樣返回:swoole tcp 客戶端測試