swoole_server->addListener

22 篇文章 1 订阅

简介

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();

结果
这里写图片描述

参考地址

https://wiki.swoole.com/wiki/page/16.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值