介绍

PHP 实现TPC Socket客户端
PHP版本:7.4.33

代码

<?php
class TPCSocketServer
{
    private $socket;

    public function connectServer($ip, $port)
    {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        return socket_connect($this->socket, $ip, $port);
    }

    public function sendMessage($message){
        return socket_write($this->socket, $message);
    }

    public function readMessage($size){
        return socket_read($this->socket, $size);
    }
    
    public function closeConnect(){
        socket_close($this->socket);
    }
}

示例

<?php
$client = new TPCSocketServer;
$client->connectServer("192.168.222.1", 3003);
$client->sendMessage("hello");
echo $client->readMessage(128);
$client->closeConnect();