socket simple principle and implementation of php

What is a socket

socket: two programs on the network connection for data exchange via a two-way communication, a connection as a socket.

Thus socket set operation is composed of two end rare, one of a client (client s) to the server.

socket works

Several key function of the socket

The key function socket 1:

      socket_create ($ net parameter 1, $ stream parameters 2, $ protocol parameter 3)

    Role: create a socket socket is a network data stream.

    Returns: a socket, or is false, parameter error warning issued E_WARNING

    php online manual where it says more clearly:

    socket_create Creates and returns a socket, also known as a communications node. A typical network connection is constituted by two sockets, one running on the client, the other runs on the server side.

    Parameter 1 is: network protocol,

    What network protocols? It's on the following three options:

    AF_INET: IPv4 network protocol. TCP and UDP can use this protocol. Generally use this, you know.

    AF_INET6: IPv6 network protocol. TCP and UDP can use this protocol.

    AF_UNIX: local protocol. High performance and low cost of IPC (interprocess communication).

    Parameter 2: socket stream, the options are:

    SOCK_STREAM  SOCK_DGRAM  SOCK_SEQPACKET  SOCK_RAW  SOCK_RDM。

    Here only the first two are explained:

    SOCK_STREAM TCP protocol sockets.

    SOCK_DGRAM UDP protocol socket.

    For more information, please link here: http: //php.net/manual/zh/function.socket-create.php

    Parameter 3: protocol agreement, the options are:

    SOL_TCP: TCP protocol.

    SOL_UDP: UDP protocol.

    As can be seen here, in fact, the second parameter and the third parameter socket_create function is associated.

    For example, if the first argument you use IPv4 protocol: AF_INET, then the second argument is the application of TCP socket: SOCK_STREAM,

    Then the third parameter must be used SOL_TCP

The key function 2:

    socket_connect ($ socket parameters 1, $ ip parameter 2, $ port 3 parameters)

    Action: a socket connection, returns true or false

    Parameter 1: socket_create function return value

    Parameter 2: ip address

    Parameter 3: No. Port

3 key functions:

    socket_bind ($ socket parameters 1, $ ip parameter 2, $ port 3 parameters)

    Action: binding a socket, the return value is true or false

       Parameter 1: socket_create function return value

    Parameter 2: ip address

    Parameter 3: No. Port

 

The key function 4:

    socket_listen ($ socket parameters 1, $ backlog parameter 2)

    Action: a listening socket, the return value is true or false

    Parameter 1: socket_create function return value

    Parameter 2: The maximum number of sockets listening

The key function 5:

    socket_accept($socket)

    Role: receiving socket resource information, the successful return information resource socket, failed to false

        Arguments: socket_create return value

 

The key function 6:

    socket_read ($ socket parameters 1, $ length parameter 2)

    Role: reading resource information socket,

    Returns: the success of the socket resource information into a string, failed to false

      Parameter 1: socket_create or function return value socket_accept

    Length of the string read: 2 Parameter

 

The key function 7:

    socket_write ($ socket parameters 1, $ msg parameter 2, $ strlen 3 parameters)

    Effect: the data is written in the socket

    Return Value: returns the byte length of the string of success, failure is false

      Parameter 1: socket_create or function return value socket_accept

    Parameter 2: String

    3 parameters: the length of the string

 

The key function 8:

    socket_close($socket)

    Role: Closes the socket

    Returns: Returns true if successful, failed to false

        Arguments: socket_create return value or socket_accept

 

    The eight core function is a function of the socket, here are two relatively important function

    socket_last_error ($ socket), parameter socket_create return value, is to get a socket of the last error code number, the return value of the socket code

    socket_strerror ($ code), the parameters for the function return value socket_last_error, information acquired code string, error value is returned in the socket

 

Server-side scripting, server_socket.php

? < PHP
 // Create a stream socket socket server-side, net protocol IPv4, protocol protocol TCP 
$ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); 

    / * Bind received stream socket host and port, and the client corresponding * / 
    IF (socket_bind ( $ Socket , '127.0.0.1', 8888) == to false ) {
         echo 'the bind Server Fail:'. socket_strerror (socket_last_error ());
         / * 127.0.0.1 here is the local host test, if you have more than one computer, you can write IP address * / 
    } 
    // listening socket stream 
    IF (socket_listen ( $ socket , 4) == false ) {
         echo 'the listen Server Fail:'.socket_strerror (() socket_last_error); 
    } 
// allow the server to obtain an unlimited pass over client information 
do {
     / * receiving client pass over the information * / 
    $ accept_resource = socket_accept ( $ socket );
     / * action is to accept socket_bind socket_accept () bound to the host sent over socket stream * / 

    IF ( $ accept_resource ! == to false ) {
         / * read resource clients pass over, and into the string * / 
        $ string = socket_read ( $ accept_resource , 1024 );
         / * socket_read function is to read socket_accept () resources and convert it to a string * / 

        echo 'the receive Server iS:'. $ string. Value is PHP_EOL ; // value is PHP_EOL for php of predefined constants linefeed 
        IF ( $ String =! To false ) {
             $ return_client = 'the receive Server IS:'. $ String . Value is PHP_EOL ;
             / * write information to the socket stream socket_accept also is feedback information to socket_bind () bound host client * / 
            socket_write ( $ accept_resource , $ return_client , strlen ( $ return_client ));
             / * socket_write role is to write information to the socket socket_create flow, or to socket_accept sleeved stream writing information * / 
        } the else {
             echo'socket_read IS Fail' ; 
        } 
    / * socket_close socket_create effect is off () or socket_accept () socket established stream * / 
        socket_close ( $ accept_resource ); 
    } 
} the while ( to true ); 
socket_close ( $ Socket );

 ?>

Tip: Note that the order of execution socket_bind, socket_listen, socket_accept above three functions can not be changed, that is

Must perform socket_bind, then execute socket_listen, and finally execute socket_accept

 

Client-side script, client_socket.php

? < PHP
     // Create a stream socket sockets 
    $ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
     / * *************** set socket connectivity options, these two steps you may be omitted ************ * / 
     // receiving socket stream maximum timeout 1 second, followed by a unit of microsecond timeout is set to zero to indicate whether it 
    socket_set_option ( $ Socket , SOL_SOCKET , SO_RCVTIMEO, Array ( "sec" =>. 1, "usec" => 0 ));
      // send a stream socket 6 seconds maximum timeout 
    socket_set_option ( $ Socket , SOL_SOCKET, SO_SNDTIMEO, Array ( "sec" => . 6, "usec" => 0 ));
     / * *************** socket connection option is provided, the two steps you can omit ********** ** * / 

    //Socket stream connection service side, this step is to make the stream socket client and server to establish contact 
    IF (socket_connect ( $ socket , '127.0.0.1', 8888) == false ) {
         echo 'Connect Fail massege:'. Socket_strerror (socket_last_error ()); 
    } the else {
         $ Message = 'the Hello, Socket! This is a test! ' ;
         // into GBK encoding, processing garbage problem, depending on your coding the case may be, each person is different encoding 
        // $ message = mb_convert_encoding ($ message ,' GBK ',' UTF-8 '); 
        // string information is written to the server 

        IF (socket_write ( $ Socket , $ message , strlen ( $ message )) == to false ) {
             echo'Write to Fail'. socket_strerror (socket_last_error ()); 

        } the else {
             echo . 'Client Write Success' value is PHP_EOL ;
             // read back to the server socket stream information 
            the while ( $ the callback = socket_read ( $ Socket , 1024 ) ) {
                 echo 'return Message Server IS:'. value is PHP_EOL . $ the callback ; 
            } 
        } 
    } 
    socket_close ( $ Socket ); // work is completed, close the socket stream
 
>?

 

Test results

Postscript added:

socket_set_option ($ socket parameters 1, $ level parameter 2, $ optname parameter 3, $ optval parameter 4)

This function returns a data stream to the socket set options, it is still a very important function.

参数1:socket_create或者socket_accept的函数返回值

参数2:SOL_SOCKET,好像只有这个选项

参数3与参数4是相关联的,

参数3可为:SO_REUSEADDR  SO_RCVTIMEO     S0_SNDTIMEO

解释一下:

SO_REUSEADDR  是让套接字端口释放后立即就可以被再次使用

        参数3假如是这个,则参数4可以为true或者false

SO_RCVTIMEO   是套接字的接收资源的最大超时时间

SO_SNDTIMEO   是套接字的发送资源的最大超时时间

  参数3假如是这两个,则参数4是一个这样的数组array('sec'=>1,'usec'=>500000)

  数组里面都是设置超时的最大时间,不过,一个是秒为单位,一个是微秒单位,作用都一样

 

 

 

Guess you like

Origin www.cnblogs.com/jhy-ocean/p/11425718.html