全部
常见问题
产品动态
精选推荐

【workerman源码分析】异步UDP连接类AsyncUdpConnection.php

管理 管理 编辑 删除
<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Workerman\Connection;
 
use Workerman\Events\EventInterface;
use Workerman\Worker;
use Exception;
 
/**
 * 异步Udp连接
 */
class AsyncUdpConnection extends UdpConnection
{
    /**
     * socket连接成功建立时调用
     *
     * @var callback
     */
    public $onConnect = null;
 
    /**
     * socket连接关闭时调用
     *
     * @var callback
     */
    public $onClose = null;
 
    /**
     *是否连接
     *
     * @var bool
     */
    protected $connected = false;
 
    /**
     * 文本选项
     *
     * @var array
     */
    protected $_contextOption = null;
 
    /**
     * 构造方法
     *
     * @param string $remote_address
     * @throws Exception
     */
    public function __construct($remote_address, $context_option = null)
    {
        // 获取应用层通信协议和监听地址。
        list($scheme, $address) = explode(':', $remote_address, 2);
        // 检查应用层协议类
        if ($scheme !== 'udp') {
            $scheme         = ucfirst($scheme);
            $this->protocol = '\\Protocols\\' . $scheme;
            if (!class_exists($this->protocol)) {
                $this->protocol = "\\Workerman\\Protocols\\$scheme";
                if (!class_exists($this->protocol)) {
                    throw new Exception("class \\Protocols\\$scheme not exist");
                }
            }
        }
        
        $this->_remoteAddress = substr($address, 2);
        $this->_contextOption = $context_option;
    }
    
    /**
     * udp包
     *
     * @param resource $socket
     * @return bool
     */
    public function baseRead($socket)
    {
        $recv_buffer = stream_socket_recvfrom($socket, Worker::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
        if (false === $recv_buffer || empty($remote_address)) {
            return false;
        }
        
        if ($this->onMessage) {
            if ($this->protocol) {
                $parser      = $this->protocol;
                $recv_buffer = $parser::decode($recv_buffer, $this);
            }
            ConnectionInterface::$statistics['total_request']++;
            try {
                call_user_func($this->onMessage, $this, $recv_buffer);
            } catch (\Exception $e) {
                Worker::log($e);
                exit(250);
            } catch (\Error $e) {
                Worker::log($e);
                exit(250);
            }
        }
        return true;
    }
 
    /**
     * 发送数据
     *
     * @param string $send_buffer
     * @param bool   $raw
     * @return void|boolean
     */
    public function send($send_buffer, $raw = false)
    {
        if (false === $raw && $this->protocol) {
            $parser      = $this->protocol;
            $send_buffer = $parser::encode($send_buffer, $this);
            if ($send_buffer === '') {
                return null;
            }
        }
        if ($this->connected === false) {
            $this->connect();
        }
        return strlen($send_buffer) === stream_socket_sendto($this->_socket, $send_buffer, 0);
    }
    
    
    /**
     * 关闭连接
     *
     * @param mixed $data
     * @param bool $raw
     *
     * @return bool
     */
    public function close($data = null, $raw = false)
    {
        if ($data !== null) {
            $this->send($data, $raw);
        }
        Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
        fclose($this->_socket);
        $this->connected = false;
        // 尝试发出onClose回调。
        if ($this->onClose) {
            try {
                call_user_func($this->onClose, $this);
            } catch (\Exception $e) {
                Worker::log($e);
                exit(250);
            } catch (\Error $e) {
                Worker::log($e);
                exit(250);
            }
        }
        $this->onConnect = $this->onMessage = $this->onClose = null;
        return true;
    }
 
    /**
     * 连接
     *
     * @return void
     */
    public function connect()
    {
        if ($this->connected === true) {
            return;
        }
        if ($this->_contextOption) {
            // 创建资源流上下文
            $context = stream_context_create($this->_contextOption);
            // 创建socket客户端
            $this->_socket = stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg,
                30, STREAM_CLIENT_CONNECT, $context);
        } else {
            $this->_socket = stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg);
        }
 
        if (!$this->_socket) {
            Worker::safeEcho(new \Exception($errmsg));
            return;
        }
        if ($this->onMessage) {
            Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
        }
        $this->connected = true;
        // 尝试发出onConnect回调。
        if ($this->onConnect) {
            try {
                call_user_func($this->onConnect, $this);
            } catch (\Exception $e) {
                Worker::log($e);
                exit(250);
            } catch (\Error $e) {
                Worker::log($e);
                exit(250);
            }
        }
    }
 
}


请登录后查看

CRMEB-慕白寒窗雪 最后编辑于2023-03-06 15:29:08

快捷回复
回复({{post_count}}) {{!is_user ? '我的回复' :'全部回复'}}
排序 默认正序 回复倒序 点赞倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}}

作者 管理员 企业

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest==1? '取消推荐': '推荐'}}
沙发 板凳 地板 {{item.floor}}#
{{item.user_info.title}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
{{item.like_count}}
{{item.showReply ? '取消回复' : '回复'}}
删除
回复
回复

{{itemc.user_info.nickname}}

{{itemc.user_name}}

作者 管理员 企业

回复 {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}   {{itemc.ip_address}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回复' : '回复'}}
删除
回复
回复
查看更多
回复
回复
2021
{{like_count}}
{{collect_count}}
添加回复 ({{post_count}})

相关推荐

快速安全登录

使用微信扫码登录
{{item.label}} {{item.label}} {{item.label}} 板块推荐 常见问题 产品动态 精选推荐 首页头条 首页动态 首页推荐
加精
取 消 确 定
回复
回复
问题:
问题自动获取的帖子内容,不准确时需要手动修改. [获取答案]
答案:
提交
bug 需求 取 消 确 定

微信登录/注册

切换手机号登录

{{ bind_phone ? '绑定手机' : '手机登录'}}

{{codeText}}
切换微信登录/注册
暂不绑定
CRMEB客服

CRMEB咨询热线 咨询热线

400-8888-794

微信扫码咨询

CRMEB开源商城下载 源码下载 CRMEB帮助文档 帮助文档
返回顶部 返回顶部
CRMEB客服