Basic knowledge of PHP socket network programming (2): socket function

Time:2021-6-7

explain

  • We all know that we can realize data exchange between two machines through IP, port, etc., but how to operate specifically, the system provides us with socket interface, which can be realized by calling socket function.
  • The socket extension of PHP is very similar to that of C. If you can’t find any information about PHP, you can learn from the socket function of C, for example:C language socket programming guide
  • PHPSocket document, there are many functions in the document, we only look for the function of the main communication process to understand its process, other functions can be used later to view

Communication process


Picture quoted fromSockets Baidu Encyclopedia entryThe flow of TCP communication, other ways of communication can be referred to

correlation function

  • Server related functions

    • socket_create ( int $domain , int $type , int $protocol ) : resource

      • Create a socket, such as$socket = socket_create(AF_INET, SOCK_STREAM, 0);
      • $domain is a choiceIP4perhapsIP6perhapsUNIX local communicationYou should know the parameters if you have configured nginxfastcgi_passThere are two ways to connect PHP FPM, one is TCP, the other is UNIX socket, which corresponds to the IP mode and UNIX local mode here
      • $type isSOCK_STREAM(TCP) orSOCK_DGRAM(UDP) or something
      • $protocol is generally 0, which is an IP protocol.
      • The above statement creates a TPC socket with IP4 address, and you can check the document for more parameters.
    • socket_bind ( resource $socket , string $address [, int $port = 0 ] ) : bool

      • Bind the socket created above to the specific IP and port, and the client needs to fill in the IP and interface when connecting
    • socket_listen ( resource $socket [, int $backlog = 0 ] ) : bool

      • Listen for client links( This function is not needed for UDP communication.)
      • The second parameter, backlog, is the size of the handshake queue before accept. If we have configured PHP FPM, we should have contacted it. It is calledlisten.backlog This parameter corresponds to socket_ For the second parameter in listen, the default value of PHP FPM is 511, while the default value of workerman is 102400
      • Related references:socket_ The use of the second parameter in listenWhat is the purpose of the backup parameter in TCP socket?
    • socket_accept ( resource $socket ) : resource

      • Receive client connection (this function is not needed for UDP communication)
        At this point, you can connect with the client to read and write. It should be noted that the return value is a new socket, and the subsequent read and write is carried out under the new socket instead of the socket created at the beginning.
  • Client related functions

    • socket_connect ( resource $socket , string $address [, int $port = 0 ] ) : bool
      • When a client connects to a server, just like the server, it first calls thesocket_createCreate a socket, and then call this function to connect to the server
  • Read write function

    • socket_send ( resource $socket , string $buf , int $len , int $flags ) : int
      • Send data to socket
    • socket_write ( resource $socket , string $buffer [, int $length = 0 ] ) : int
      • Write data to socket
    • The last two functions are basically the same, socket_ If the last $flags parameter in send is set to 0, it is equal to socket_ Write. There are very few online comparisons about these two functions, which can’t be found. What’s more, looking at the PHP source code, you will find that there are some internal differences between the two methods,socket_writeQuoted in#ifndef PHP_WIN32To determine if it is a non windows system, call thewriteMethod, and windows system calls thesendMethod, butsocket_sendThere is no judgment and the system is called uniformlysendI don’t understandsocket_writeWhy should we add judgment?
    • socket_sendto( resource $socket , string $buf , int $len , int $flags , string $addr [, int $port = 0 ] ) : int
      • Mainly when UDP communication, send data
    • socket_recv( resource $socket , string &$buf , int $len , int $flags ) : int
      • When receiving data from socket, it should be noted that the return value is int, which indicates the number of bytes received, and the content is stored in the parameter $buf of the second reference type
    • socket_read ( resource $socket , int $length [, int $type = PHP_BINARY_READ ] ) : string
      • Read data from socket, and the returned result is the read data
    • The above two functions are also very similar, except for the difference in return value, socket_ The last $flags of recv are 0 and socket_ The last $type of read is PHP_ BINARY_ The read data is the same, but if the flags or type change, it is not necessarily the same.
    • socket_recvfrom ( resource $socket , string &$buf , int $len , int $flags , string &$name [, int &$port ] ) : int
      • Mainly UDP communication, receiving data
  • Other common functions

    • socket_close ( resource $socket ) : void
      • Close socket
    • socket_set_nonblock( resource $socket ) : bool
      • Set to non blocking
    • socket_set_block( resource $socket ) : bool
      • Set to block
    • The functions of the above two influences are as follows:socket_connectsocket_acceptAnd all the aboveRead write function, withsocket_acceptFor example, blocking means that after calling this method, if the client is not received, the method will be stuck and wait for the client to join before proceeding to the next action. Non blocking means that if there is no client to join, it will directly return false. The details will be summarized in the IO model later
    • socket_select( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] ) : int
      • Call system select() related IO model
      • The details will be summarized in the IO model later

Examples

  • Server socket_ service.php:
  • Client socket_ client.php:
  • Above is a simple example code, running in command line cli modephp socket_service.php, and then run in a new windowphp socket_client.phpYou can see that the client receives the data sent by the server and displays it.
  • In ordinary programming, we usually try to avoid using while (true) as much as possible. We are afraid that infinite loop will lead to stuck, but it is often used in network programming. In fact, as long as it is well controlled, it is OK. The reason why we can use it is because of the default socket_ Accept is blocked, that is, when there is no client access, it will be stuck here waiting for access, so it will not cause performance impact.
  • You can also look at PHPExamples in the document, follow the prompts to test.
  • Through the example, we can see that it can be connected, but there are great limitations. Only one server can connect to one client. If you want to connect multiple clients at the same time, it’s not OK. (the simple code above may not be obvious. After all, after connecting, it will be closed and disconnected. However, the example in the PHP document will be obvious. Open several windows at the same timetelnetThe solution is to use fork subprocess or IO multiplexing, which will be summarized later.

relation