php socket


class MySocket
{
    private \Socket $socket;
    public string $ip = '';
    public int $port = 0;

    public function conn(): array
    {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 1, 'usec' => 0]);
        socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => 6, 'usec' => 0]);
        try {
            if (!socket_connect($this->socket, $this->ip, $this->port)) return err(1, $this->ip . ':' . $this->port);
        } catch (\Exception $e) {
            return err(2, $e->getMessage());
        }
        return succ();
    }

    public function send($data): array
    {
        //发送请求
        $write = socket_write($this->socket, $data, strlen($data));
        if (!$write) return err(1, 'socket_write failed');
        //读取约定好的头长度
        $head = socket_read($this->socket, 10);
        if ($head === false) return err(2, 'header err');
        //读取具体数据
        $data = socket_read($this->socket, $head);
        if ($data === false) return err(3, 'boday err');
        return succ($data);
    }

    public function close()
    {
        socket_close($this->socket);
    }
}

这对当时的我是有多重要哦 还写了篇文章


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注