Home  >  Article  >  Backend Development  >  PHP+Socket series realizes data transmission between client and server

PHP+Socket series realizes data transmission between client and server

藏色散人
藏色散人forward
2023-02-02 11:35:014976browse

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;
    }
}

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;
}

Syntax explanation

socket_create

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

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

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

    参数:

    • 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

    在使用 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

    当有新的客户端连接时,返回一个新的 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

    使用套接字实例发起到 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

    传输数据至指定套接字

    参数:

    • 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

    从套接字资源内读取数据

    参数:

    • 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

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

    参数:

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

    返回值:

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

    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

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:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete