search
HomeBackend DevelopmentPHP TutorialHow to use protobuf-php and socket
How to use protobuf-php and socketMar 28, 2018 pm 01:28 PM
socketInstructions

This article mainly shares with you how to use protobuf-php and socket. It mainly explains it to you in the form of code. I hope it can help you.

vi login.proto

package login;
message ReqCheckVerifyVerLoginClient
{
 required int32 game = 1; ///< 游戏类型编号 required bytes version = 2; ///< 游戏版本号}
message AnsCheckVerifyVerLoginClient
{
     required uint32 ret_code = 1;  //返回码     optional uint32 forbid_flag = 2; //冻结时间     optional uint32 time_diff = 3;  //剩余解封时间}

protoc --plugin=/usr/local/php/bin/protoc-gen-php --php_out=. -I. login.proto

Get login.php

namespace login {  class ReqCheckVerifyVerLoginClient extends \DrSlump\Protobuf\Message {    /**  @var int */    public $game = null;    
    /**  @var string */    public $version = null;    
    /** @var \Closure[] */    protected static $__extensions = array();.........

Use login.php

function.php

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2018/3/23 * Time: 19:26 */require &#39;socket.php&#39;;require &#39;structNum.php&#39;;function socket($ip,$port,$packed){    try{
        $socket = Socket::singleton();
        $socket->connect($ip,$port);        if(count($packed) >1){            foreach ($packed as $key){
                $sockResult = $socket->sendRequest($key);// 将包发送给服务器                sleep(3);
            }
        }
        $getrepost = $socket->getResponse();
        $socket->disconnect (); //关闭链接    } catch (Exception $e) {
        var_dump($e);
        $this->log_error(" error send to server".$e->getMessage());
    }    return $getrepost;
}function unPackData($data){
    $rev_len = unpack("L*",substr($data,0,4));
    $rev_num = unpack("S*",substr($data,4,2));
    $rev_data = substr($data,6,2);
    $data_array = array(        &#39;num&#39; =>$rev_num,        &#39;data&#39;=>$rev_data
    );    return $data_array;
}
$structNum;function StructNum($num){
    $class = $GLOBALS[&#39;structNum&#39;][$num];    return $class;
}

socket.php

<?phpdefine("CONNECTED", true);
define("DISCONNECTED", false); Class Socket {     private static $instance;     private $connection = null;     private $connectionState = DISCONNECTED;     private $defaultHost = "192.168.128.198";     private $defaultPort = 9301;     private $defaultTimeOut = 60;     public $debug = false;     public function __construct()
     {
     }     /**      * Singleton pattern. Returns the same instance to all callers      *      * @return Socket      */     public static function singleton()
     {         if (self::$instance == null || ! self::$instance instanceof Socket)
         {             self::$instance = new Socket();
         }         return self::$instance;
     }     public function connect($serverHost=false,$serverPort=false,$timeOut=false)
     {         if($serverHost == false)
         {             $serverHost = $this->defaultHost;
         }         if($serverPort == false)
         {             $serverPort = $this->defaultPort;
         }
         $this->defaultHost = $serverHost;
         $this->defaultPort = $serverPort;         if($timeOut == false)
         {             $timeOut = $this->defaultTimeOut;
         }
         $this->connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);         if(socket_connect($this->connection,$serverHost,$serverPort) == false)
         {
             $errorString = socket_strerror(socket_last_error($this->connection));
             $this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}");
         }else{
             $this->_throwMsg("Socket connected!");
         }
         $this->connectionState = CONNECTED;
     }     /**      * Disconnects from the server      *      * @return True on succes, false if the connection was already closed      */     public function disconnect()
     {         if($this->validateConnection())
         {
             socket_close($this->connection);
             $this->connectionState = DISCONNECTED;
             $this->_throwMsg("Socket disconnected!");             return true;
         }         return false;
     }     public function sendRequest($data)
     {         if($this->validateConnection())
         {
              $result = socket_write($this->connection,$data,strlen($data));              return $result;
         }else{
             $this->_throwError("Sending command \"{$data}\" failed.<br>Reason: Not connected");
         }
     }     public function getResponse()
     {         if($this->validateConnection())
         {             if( ($ret = socket_read($this->connection,8192)) == false){
                 $this->_throwError("Receiving response from server failed.<br>Reason: Not bytes to read");                 return false;
             } else{                 return $ret;
            }
         }
     }     public function isConn()
     {         return $this->connectionState;
     }     public function getUnreadBytes()
     {
         $info = socket_get_status($this->connection);         return $info[&#39;unread_bytes&#39;];
     }     public function getConnName(&$addr, &$port)
     {         if ($this->validateConnection())
         {
             socket_getsockname($this->connection,$addr,$port);
         }
     }     public function waitForResponse()
     {         if($this->validateConnection())
         {             return socket_read($this->connection, 2048);
         }
         $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");         return false;
     }     /**      * Validates the connection state      *      * @return bool      */     private function validateConnection()
     {         return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED));
     }     /**      * Throws an error      *      * @return void      */     private function _throwError($errorMessage)
     {         echo "Socket error: " . $errorMessage;
     }     /**      * Throws an message      *      * @return void      */     private function _throwMsg($msg)
     {         if ($this->debug)
         {             echo "Socket message: " . $msg . "\n\n";
         }
     }     /**      * If there still was a connection alive, disconnect it      */     public function __destruct()
     {
         $this->disconnect();
     }
 }

structNum.php // Class Dictionary

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2018/3/26 * Time: 17:54 */$structNum = array(    46=>new \login\ReqCheckVerifyVerLoginClient(),    47=>new \login\AnsCheckVerifyVerLoginClient(),
);

vi use_login.php

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2018/3/26 * Time: 15:20 */require_once &#39;DrSlump/Protobuf.php&#39;;
\DrSlump\Protobuf::autoload();require &#39;login.php&#39;;require &#39;function.php&#39;;//实例化 class 46$login = StructNum(46);
$login->setGame(3);
$login->setVersion(&#39;0.0.1&#39;);
$first_data = pack("I*",24063);//一个可识别的ID
$first_len = pack("I*",4);
$second_data = $login->serialize();//序列化
$second_len = pack("I*",strlen($second_data) + 2);
$second_num = substr(pack("I*",46),0,2);
$first_pack = $first_len.$first_data; //字节 包体
$second_pack = $second_len.$second_num.$second_data;//长度 协议 内容(protobuf)
$port = 9301;
$ip = "192.168.128.198";
$pack = array($first_pack,$second_pack);
$result = socket($ip,$port,$pack);//连接 发送 接受数据  数据为长度 协议 内容(protobuf)
$unPackDatas = unPackData($result);//拆分数据(按需拆分) 按 4 2 2 拆分//实例化 class 46$reLogin = StructNum($unPackDatas[&#39;num&#39;][1]);
$reLogin->parse($unPackDatas[&#39;data&#39;]);//拆分后的内容 再反序列化
$reLogin->getRetCode();
$reLogin->getForbidFlag();
$reLogin->clearTimeDiff();
var_dump($reLogin);

Related recommendations:

Detailed explanation of socket communication in php

PHP Socket server construction and test example sharing

Simple method of using Socket in PHP

The above is the detailed content of How to use protobuf-php and socket. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python的socket与socketserver怎么使用Python的socket与socketserver怎么使用May 28, 2023 pm 08:10 PM

一、基于TCP协议的socket套接字编程1、套接字工作流程先从服务器端说起。服务器端先初始化Socket,然后与端口绑定(bind),对端口进行监听(listen),调用accept阻塞,等待客户端连接。在这时如果有个客户端初始化一个Socket,然后连接服务器(connect),如果连接成功,这时客户端与服务器端的连接就建立了。客户端发送数据请求,服务器端接收请求并处理请求,然后把回应数据发送给客户端,客户端读取数据,最后关闭连接,一次交互结束,使用以下Python代码实现:importso

PHP+Socket系列之IO多路复用及实现web服务器PHP+Socket系列之IO多路复用及实现web服务器Feb 02, 2023 pm 01:43 PM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了IO多路复用,以及php+socket如何实现web服务器?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

怎么使用Spring Boot+Vue实现Socket通知推送怎么使用Spring Boot+Vue实现Socket通知推送May 27, 2023 am 08:47 AM

SpringBoot端第一步,引入依赖首先我们需要引入WebSocket所需的依赖,以及处理输出格式的依赖com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket第二步,创建WebSocket配置类importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

php socket无法连接怎么办php socket无法连接怎么办Nov 09, 2022 am 10:34 AM

php socket无法连接的解决办法:1、检查php是否开启socket扩展;2、打开php.ini文件,检查“php_sockets.dll”是否被加载;3、取消“php_sockets.dll”的注释状态即可。

PHP+Socket系列之实现客户端与服务端数据传输PHP+Socket系列之实现客户端与服务端数据传输Feb 02, 2023 am 11:35 AM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了什么是socket?php+socket如何实现客户端与服务端数据传输?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

利用PHP和Socket实现实时文件传输技术研究利用PHP和Socket实现实时文件传输技术研究Jun 28, 2023 am 09:11 AM

随着互联网的发展,文件传输成为人们日常工作和娱乐中不可或缺的一部分。然而,传统的文件传输方式如邮件附件或文件分享网站存在一定的限制,无法满足实时性和安全性的需求。因此,利用PHP和Socket技术实现实时文件传输成为了一种新的解决方案。本文将介绍利用PHP和Socket技术实现实时文件传输的技术原理、优点和应用场景,并通过具体案例来演示该技术的实现方法。技术

C#中常见的网络通信和安全性问题及解决方法C#中常见的网络通信和安全性问题及解决方法Oct 09, 2023 pm 09:21 PM

C#中常见的网络通信和安全性问题及解决方法在当今互联网时代,网络通信已经成为了软件开发中必不可少的一部分。在C#中,我们通常会遇到一些网络通信的问题,例如数据传输的安全性、网络连接的稳定性等。本文将针对C#中常见的网络通信和安全性问题进行详细讨论,并提供相应的解决方法和代码示例。一、网络通信问题网络连接中断:网络通信过程中,可能会出现网络连接的中断,这会导致

PHP+Socket系列之实现websocket聊天室PHP+Socket系列之实现websocket聊天室Feb 02, 2023 pm 04:39 PM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了怎么使用php原生socket实现一个简易的web聊天室?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)