Home > Backend Development > PHP Tutorial > Commonly used functions in php socket programming and the implementation of simple c/s interaction

Commonly used functions in php socket programming and the implementation of simple c/s interaction

不言
Release: 2023-04-03 12:40:02
Original
1652 people have browsed it

The content of this article is about commonly used functions in php socket programming and the implementation of simple c/s interaction. The content is very detailed. Friends in need can refer to it. I hope it can help you.

Socket Introduction

Official explanation of Socket:
The most commonly used solution in network programming is the Client/Server (client/server) model. In this scenario the client application requests services from the server program. A service program usually listens for requests for the service at a well-known address. That is to say, the service process remains dormant until a client makes a connection request to the service's address. At this moment, the service program is "awakened" and provides services to the client - reacting appropriately to the client's request. In order to facilitate network programming of this Client/Server model, in the early 1990s, Microsoft and several other companies jointly developed a set of network programming interfaces under WINDOWS, namely the Windows Sockets specification. It is not a network protocol, but a network programming interface. A set of open network programming interfaces under Windows that support multiple protocols. Now Winsock has basically become protocol-independent. You can use Winsock to call functions of multiple protocols, but the TCP/IP protocol is more commonly used. Socket actually provides a communication port in the computer through which it can communicate with any computer that has a Socket interface. The application transmits on the network, and the information received is realized through this Socket interface

We can simply understand Socket as a pipe that can connect different computer applications on the network, and transfer a bunch of data from If the A end of the pipe is thrown in, it will come out from the B end of the pipe (it can also come out from the C, D, E, F... ends).

Note: We will use different words to modify socket in different contexts. You only need to have a concept of it, because socket itself has no real meaning. Entity

Socket function introduction

Socket communication will proceed through several stages: Socket creation, Socket binding, Socket monitoring, Socket sending and receiving, and Socket closing. We list them below. Several common functions that are most commonly used and essential in PHP network programming are further explained.

socket_create

TODO: Create a new socket resource
Function prototype: resource socket_create (int $domain, int $type, int $protocol)
It contains three parameters, as follows:

  • domain: AF_INET, AF_INET6, AF_UNIX, the definition of AF is address family, address Family means, we commonly use ipv4, ipv6

  • type: SOCK_STREAM, SOCK_DGRAM, etc. The most commonly used one is SOCK_STREAM, a SOCKET type based on byte stream, It is also the type used by TCP protocol

  • protocol: SOL_TCP, SOL_UDP This is the specific transmission protocol used. Generally, we choose TCP for reliable transmission, and we generally choose UDP protocol for game data transmission

socket_bind

TODO: Bind the created socket resource to a specific ip address and port
Function prototype: bool socket_bind (resource $socket, string $ address [, int $port = 0 ] )

It contains three parameters, as follows:

  • socket: Use socket_create The created socket resource can be considered as the id corresponding to the socket

  • address: ip address

  • port: listening port number, WEB server default Port 80

socket_listen

TODO: Monitor the sending and receiving operations of socket resources at a specific address
Function prototype: bool socket_listen (resource $socket [ , int $backlog = 0 ] )

It contains two parameters, as follows:

  • socket: Created using socket_create Socket resource

  • backlog: The maximum length of the connection queue waiting to be processed

socket_accept

TODO: After listening, receive a The upcoming new connection, if the connection is successfully established, will return a new socket handle (you can understand it as a child process, usually the parent process is used to receive new connections, and the child process is responsible for specific communication)
Function prototype: resource socket_accept ( resource $socket )

  • socket: socket resource created using socket_create

socket_write

TODO: Send the specified data to the corresponding socket pipe
Function prototype: int socket_write (resource $socket, string $buffer [, int $length])

  • socket: socket resource created using socket_create

  • buffer: written to socket resource Data in

  • length: Controls the length of buffer written to the socket resource, if the length is greater than buffer’s capacity, take the capacity of buffer

socket_read

TODO: Get the transmitted data
Function prototype: int socket_read (resource $socket, int $length)

  • socket: The socket resource created using socket_create

  • length: buffer# in the socket resource ##The length

socket_close

TODO: Close the socket resource

Function prototype:
void socket_close (resource $socket)

  • socket: The resources generated by

    socket_accept or socket_create cannot be used to close stream resources

stream_socket_server

Since the process of creating a SOCKET is always socket, bind, and listen, PHP provides a very convenient function to create, bind ports, and listen to ports at once

Function prototype:

resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )

  • local_socket: protocol name://address:port number

  • errno: error code

  • errstr: Error message

  • #flags: Only use part of the function

  • context: Resource stream created using the

    stream_context_create function Context

socket implements C/S interaction

Based on the above functions, we can easily build a socket communication program (here I hope Readers can create a separate directory such as

socket (because we will create many files later). We first edit a server program server.php, as follows:

<?php date_default_timezone_set("Asia/Shanghai");
error_reporting(E_NOTICE );

/*  确保在连接客户端时不会超时   */
set_time_limit(0);

$ip = &#39;127.0.0.1&#39;;
$port = 8090;

/*
 +-------------------------------
 *    @socket通信整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_bind      
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 */

/*----------------    以下操作都是手册上的    -------------------*/
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
    echo "socket_create() Why failure is:".socket_strerror($sock)."\n";
}

if(($ret = socket_bind($sock,$ip,$port)) < 0) {
    echo "socket_bind() Why failure is:".socket_strerror($ret)."\n";
}

if(($ret = socket_listen($sock,4)) < 0) {
    echo "socket_listen() Why failure is:".socket_strerror($ret)."\n";
}

echo "Start time:".date(&#39;Y-m-d H:i:s&#39;) . PHP_EOL;
echo "Listening at ".$ip.&#39;:&#39;.$port.PHP_EOL;


do {
    /*  创建新的连接  */
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
        break;
    } else {
        
    # 连接成功输出 Socket id
    $i = (int)$msgsock;
    echo "welcome client $i";

        # 向客户端通信(反馈)
        $msg ="连接成功!\n";
        socket_write($msgsock, $msg, strlen($msg));
    }
    socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Copy after login
Then Edit a client program

client.php as follows:

<?php set_time_limit(0);
$port = 8090;
$ip = "127.0.0.1";

/*
 +-------------------------------
 *    客户端 socket 连接整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 */


/**
 * @socket_connect:客户端发起套接字连接
 * @param socket  resource $socket       创建的$socket资源
 * @param address string   SOCK_STREAM   IP地址|Unix套接字
 * @param port    int                    端口
 */

/**
 * @socket_create:创建并返回一个套接字
 * @param domain   string AF_INET         IPV4 网络协议
 * @param type     string SOCK_STREAM     全双工字节流(可用的套接字类型)
 * @param protocol string SOL_TCP         具体协议(IPV4下的TCP协议)
 * @param return   套接字
 */

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}else {
    echo "try to connect &#39;$ip&#39; port: &#39;$port&#39;...\n";
}


$result = socket_connect($socket, $ip, $port);  #socket_connect的返回值应该是boolean值
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
    # 连接成功输出提示信息
    echo "connect successfully\n";

    # 向服务端发送数据
    socket_write($socket, " hello ", 1024);

    # 获取服务端数据
    $result = socket_read($socket, 1024);
    echo "服务器回传数据为:" . $result;


    echo "CLOSE SOCKET...\n";
    socket_close($socket);
    echo "CLOSE OK\n";    
    
}



?>
Copy after login
Then we open the terminal (command line) and enter the file directory to execute in sequence:

php server.php
php client.php
Copy after login
The running effect is as follows:

Commonly used functions in php socket programming and the implementation of simple c/s interaction

NoteWhen the server is listening, the process is suspended and no other operations can be performed. You may need to start another terminal to execute the client Terminal program

Related recommendations:

How does PHP and MySql realize background data reading? (Code)

thinkphp5 uses the workerman timer to crawl regularly Get the code of the site content

The above is the detailed content of Commonly used functions in php socket programming and the implementation of simple c/s interaction. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template