swoole tcp
tcp server
<?php
/**
* Class Tcp
* Tcp服务
*/
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();
}
/**
* 监听连接事件
* @param $tcp
* @param $fd
* @param $reactor_id
*/
public function onConnect($tcp, $fd, $reactorId)
{
echo "客户端id:{$fd}连接成功,来自于线程{$reactorId}\n";
}
/**
* 监听接收事件
* @param $tcp
* @param $fd
* @param $reactor_id
* @param $data
*/
public function onReceive($tcp, $fd, $reactorId, $data)
{
echo "接收到了客户端id: {$fd} 发送的数据:{$data}";
$sendData = "服务端将客户端发送的数据原样返回:{$data}";
$tcp->send($fd, $sendData);
}
/**
* 监听关闭事件
* @param $tcp
* @param $fd
*/
public function onClose($tcp, $fd)
{
echo "客户端id: {$fd} 关闭了连接\n";
}
}
$tcp = new Tcp();
开启服务:
☁ 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
服务端将客户端发送的数据原样返回: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();
执行结果:
☁ client [master] ⚡ php tcp_client.php
请输入消息:swoole tcp 客户端测试
服务端将客户端发送的数据原样返回:swoole tcp 客户端测试