简介
Swoole提供了swoole_server::addListener来增加监听的端口。业务代码中可以通过调用swoole_server::connection_info来获取某个连接来自于哪个端口。
https://wiki.swoole.com/wiki/page/16.html
示例
$serv->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
$serv->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP);
$serv->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP);
//UnixSocket Stream
$serv->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM);
//TCP + SSL
$serv->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL);
我的代码
server
<?php
class Server
{
private $serv;
public function __construct(){
$this->serv = new swoole_server('127.0.0.1', 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
$this->serv->set(array(
'worker_num' => 4,
'daemonize' => false,
'backlog' => 128,
));
$port = $this->serv->addListener("127.0.0.1",9502,SWOOLE_SOCK_TCP);//增加一个端口
print_r($port);
$this->serv->on('Connect', array($this,'onConnect'));
$this->serv->on('Receive', array($this,'onReceive'));
$this->serv->on('Close', array($this,'onClose'));
$this->serv->start();
}
public function onConnect(swoole_server $server, int $fd, int $reactorId){
echo "连接上了";
}
public function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data){
$this->serv->send($fd,"我是服务器回复的消息");
}
public function onClose(swoole_server $server, int $fd, int $reactorId){
echo "关闭了连接";
}
}
new Server();
Client
<?php
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{
exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("我是发送的数据\n");
echo $client->recv();
$client->close();
结果