Table of Contents
php implements socket
Home Backend Development PHP Tutorial PHP+Socket series realizes data transmission between client and server

PHP+Socket series realizes data transmission between client and server

Feb 02, 2023 am 11:35 AM
php socket

This article brings you relevant knowledge about php socket. It mainly introduces what is socket? How does php socket realize client-server data transmission? Friends who are interested can take a look below. I hope it will be helpful to everyone.

Socket introduction

To achieve communication between network processes, almost all applications use sockets. Sockets are the intermediate communication between the application layer and the TCP/IP protocol family. Abstraction layer, which is a set of interfaces. In the design mode, socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the socket interface. For the user, a set of simple interfaces is all, allowing the socket to organize the data to comply with the specified Protocol

PHP+Socket series realizes data transmission between client and server

The original meaning of socket in English is "hole" or "socket". It is also commonly called "socket" and is used to describe IP addresses and ports. It is a The handle of the communication chain can be used to implement communication between different virtual machines or different computers.

Three processes of socket link

  • Server listening: IP port number

  • Client request: Send to service End IP and port connection request

  • Link confirmation: The server socket listens or receives the client socket connection request, and it will create a new process. Send the server's socket description to the client in response to the client's request. Once the client confirms this description, the connection is established. The server's socket continues to be in the listening state and continues to accept connection requests from other client sockets.

PHP+Socket series realizes data transmission between client and server

php implements socket

If you need to use socket in php, you need to add -- when compiling php enable-sockets configuration item to enable, you can use the php -m|grep sockets command to check the enabling status. For the specific compilation process, please refer to this article

Quick Experience

The simplified codes for the server and client are as follows. After running, the server will block and wait for the client to connect. The client will ask for input content on the console. After input, the information will be displayed in the service The client prints, and the client displays the content converted to uppercase. This example server and client run on the same server:

Server listening

<?php

// 创建套接字
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// 设置 ip 被释放后立即可使用
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, true);

// 绑定ip与端口
socket_bind($socket, 0, 8888);

// 开始监听
socket_listen($socket);

while (true) {
    // 接收内容
    $conn_sock = socket_accept($socket);
    socket_getpeername($conn_sock, $ip, $port);
    // echo &#39;请求ip: &#39; . $ip . PHP_EOL . &#39;端口: &#39; . $port;

    while (true) {
        // 获取消息内容
        $msg = socket_read($conn_sock, 10240);
        // TODO 处理业务逻辑

        // 将信息转为大写并原样返回客户端
        socket_write($conn_sock, strtoupper($msg));

        echo $msg;
    }
}
Copy after login

Client connection

<?php

// 创建套接字
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// 连接服务端
socket_connect($socket, &#39;127.0.0.1&#39;, 8888);

while (true) {
    // 让控制台输入内容
    fwrite(STDOUT, &#39;请输入内容:&#39;);
    $in = fgets(STDIN);

    // 向服务端发送内容
    socket_write($socket, $in);

    // 读取服务端发送的消息
    $msg = socket_read($socket, 10240);
    echo $msg;
}
Copy after login

Syntax explanation

socket_create

socket_create(int $domain,int $type, int $protocol): resource|false
Copy after login

Create and return a socket resource , also usually called a communication node. A typical socket consists of at least 2 sockets, one running on the client side and one running on the server side.

Parameters:

  • ##domain Specifies what protocol the current socket uses. The available protocols are as follows:

    DomainDescriptionAF_INETIPv4 network protocol, both TCP and UDP are available Use this protocolAF_INET6IPv6 network protocol, both TCP and UDP can use this protocolAF_UNIXLocal communication protocol, IPC with high performance and low cost
  • ##type

    User specifies the current set Type used by the interface

    typeSOCK_STREAM SOCK_DGRAMSOCK_SEQPACKETSOCK_RAWSOCK_RDM
  • protocol 设置指定 domain 套接字下的具体协议,如果所需协议是 TCP 或者 UDP,可以直接使用常量 SOL_TCPSOL_UDP,这个参数的具体值可通过 getprotobyname() 函数获取

  • 返回值

    socket_create() 正确时返回一个套接字资源,失败时返回 false。可以调用 socket_last_error() 获取错误码,错误码可以通过 socket_strerror(int $err_no) 转换为文字的错误说明。

    socket_bind

    socket_bind(resource $socket, string $address [, int $port]): bool
    Copy after login

    绑定一个地址与端口到套接字

    参数:

    • socket 使用 socket_create() 创建的套接字资源

    • address

      如果套接字是 AF_INET 族,那么 address 必须是一个四点法的 IP 地址,例如 127.0.0.10.0.0.0

      如果套接字是 AF_UNIX 族,那么 address 是 Unix 套接字一部分(例如 /tmp/my.sock

    • port (可选)

      该参数仅用于使用 AF_INET 族时,指定当前套接字监听的端口号

    返回值:

    绑定成功返回 true,失败时则返回 false,同 socket_create ,在绑定失败时可以调用 socket_last_error() 获取错误码,错误码可以通过 socket_strerror(int $err_no) 转换为文字的错误说明。

    socket_listen

    socket_listen(resource $socket [, int $backlog]): bool
    Copy after login

    在使用 socket_create() 创建套接字并使用 socket_bind() 将其绑定到名称之后,可能会告诉它侦听套接字上的传入连接。该函数仅适用于 SOCK_STREAMSOCK_SEQPACKET 类型的套接字。

    参数:

    • socket 使用 socket_create() 创建的套接字资源
    • backlog 最大数量的积压传入连接将排队等待处理,如果连接请求到达时队列已满,则客户端可能会收到指示为 ECONNREFUSED 的错误。或者,如果底层协议支持重传,则可能会忽略该请求,以便重试可能会成功。

    返回值:

    绑定成功返回 true,失败时则返回 false,可以调用 socket_last_error() 获取错误码,错误码可以通过 socket_strerror(int $err_no) 转换为文字的错误说明。

    socket_accept

    socket_accept(resource $socket): resource|false
    Copy after login

    当有新的客户端连接时,返回一个新的 socket 资源以用于与客户端通信,如有多个连接排队,则返回第一个连接,相反如果没有待处理的连接,该函数会默认阻塞当前进程,直至新的客户端连接、断开

    参数:

    • socket 使用 socket_create() 创建的套接字资源

    返回值:

    成功时返回一个新的套接字资源,错误时返回 false,可以调用 socket_last_error() 获取错误码,错误码可以通过 socket_strerror(int $err_no) 转换为文字的错误说明。

    socket_connect

    socket_connect(resource $socket, string $address [, int $port = null]): bool
    Copy after login

    使用套接字实例发起到 address 的连接

    参数:

    • socket 该参数必须是由 socket_create() 创建的 socket 实例

    • address

      如果套接字是 AF_INET 族,那么 address 必须是一个四点法的 IP 地址,例如 127.0.0.1 如果支持 IPv6 并且套接字是 AF_INET6,那么 address 也可以是一个有效的 IPv6 地址(例如 ::1

      如果套接字是 AF_UNIX 族,那么 address 是 Unix 套接字一部分(例如 /tmp/my.sock

    返回值:

    成功时返回 true, 或者在失败时返回 false

    socket_write

    socket_write(resource $socket, string $data [, int $length = null]): int|false
    Copy after login

    传输数据至指定套接字

    参数:

    • socket 使用 socket_create()socket_accept() 创建的套接字资源

    • data 要发送的内容

    • length (可选)

      可以指定发送套接字的替代字节长度。如果这个长度大于实际发送内容的长度,它将被静默地截断为实际发送内容的长度。

    返回值:

    成功时返回成功发送的字节数,或者在失败时返回 false,可以调用 socket_last_error()socket_strerror(int $err_no) 获取具体错误信息

    socket_read

    socket_read(resource $socket, int $length, int $mode = PHP_BINARY_READ): string|false
    Copy after login

    从套接字资源内读取数据

    参数:

    • socket 使用 socket_create()socket_accept() 创建的套接字资源(服务端为 socket_accept() 客户端为 socket_create()

    • length 指定最大能够读取的字节数。否则您可以使用 \r\n\0 结束读取(根据 mode 参数设置)

    • mode (可选)

      PHP_BINARY_READ (默认)- 使用系统的 recv() 函数。二进制安全地读取数据。

      PHP_NORMAL_READ - 读取到 \n\r 时停止。

    返回值:

    socket_read() 返回一个字符串,表示接收到的数据。如果发生了错误(包括远程主机关闭了连接),则返回 false,可以调用 socket_last_error()socket_strerror(int $err_no) 获取具体错误信息

    socket_close

    socket_close(resource $socket): void
    Copy after login

    关闭并销毁一个套接字资源

    参数:

    • socket 使用 socket_create()socket_accept() 创建的套接字资源

    返回值:

    推荐学习:《PHP视频教程》                                                    

    The above is the detailed content of PHP+Socket series realizes data transmission between client and server. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    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

    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)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

    PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

    How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

    Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

    7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

    If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

    How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

    This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

    A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

    What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

    What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

    See all articles
    Description
    Sequential, reliable, full-duplex, link-based byte stream, supporting data transfer flow control mechanism. The TCP protocol is based on this streaming socket.
    Support for data messages (connectionless, unreliable, fixed maximum length) UDP protocol is based on this message socket
    Sequential, reliable, full-duplex, connection-oriented, fixed maximum length data communication, the data end reads the entire data segment by receiving each data segment Packet
    Read the original network protocol. This special socket can be used to manually build any type of protocol. Generally, this socket is used To implement ICMP request
    Reliable data layer, but the arrival order is not guaranteed. General operating systems do not implement this function