Simple understanding of php socket programming

不言
Release: 2023-03-24 17:54:02
Original
1119 people have browsed it

The main content of this article is about a simple understanding of php socket programming, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it

php socket Programming is relatively difficult to understand. However, we only need to understand the socket relationship between several functions, and It shouldn’t be difficult to understand the roles they play. In the author’s opinion, socket programming is actually to establish the client and server of a network service. This is the same as The client and server of mysql are the same. You only need to understand what the client and server of mysql are. , you should be able to understand what I am going to say below.

About the network protocols involved in socket programming, what is TCP? UDPAh, whatsocketthree-way handshake, etc. There are very detailed explanations of these network protocols on the Internet. I won’t go into them here, just a screenshot. socket Let you take a look at the process diagram of establishing a socket:

         

  This picture was stolen from someone else through hard work. You must take a good look at it. At the same time, I would also like to express my gratitude to the author whose screenshot was stolen from me. I I apologize for stealing your pattern, and I hope you don't care about it. I am too lazy to draw pictures (actually it means I am not confident in my drawing skills, haha).

How does socket establish a connection? As mentioned above, the process of establishing a connection is essentially the same as the connection between the client and server of mysql. The difference from mysql is that the server and client of mysql have been edited for us, we only need to apply That's it. However, the critical moment has come. socket It provides us with nothing. The only thing it provides us is: dozens of socketfunction.

The implication is that socket Programming requires us to create the server and client ourselves, that is to say, ``socketProgramming``—— is to build one similar to mysql Server and client applications.

Having said that, I would like to ask, do you think this socket is a headache? It neither creates a server nor a client for us to apply. We have to use the functions of socket to create a network protocol suite of our own. Does it give you a headache to connect to the application? There's nothing you can do about the headache. If you need your own application, you still have to deal with socket. Haha, this is just a digression, I won’t say much, let’s get to the point.

Before you are confused by socket programming, I would like to let you take a look at several key functions of socket, Let me first explain their respective functions to you. Otherwise, if someone who has no foundation in socket reads this, I'm afraid that after reading it, you will decisively skip this article and learn about from now on. sockethas a phobia. Haha, I said more.

The key functions of socket1

  socket_create($netparameter1$streamparameter 2,$protocolparameter3)

Function: Create a socket socketword, to put it bluntly, it is a network data stream.

Return value: a socket, or false, parameter error E_WARNINGWarning

The online manual of php makes it clearer:

  socket_createCreate and return a socket, also called a communication node. A typical network connection consists of 2 sockets, one running on the client side and the other running on the server side.

The above sentence is copied from the php online manual. Do you see that the meaning here is exactly the same as the client and server that I mentioned repeatedly above? hehe.

The parameter 1 is: network protocol,

## What are the network protocols? ? Its options are the following three:

##   AF_INET:   IPv4 network protocol. TCP and UDP can both use this protocol. This is generally used, you know.

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

   AF_UNIX:  Local communication protocol. IPC (Inter-Process Communication) with high performance and low cost.

Parameter 2: Socket stream, options are:

  SOCK_STREAM SOCK_DGRAM SOCK_SEQPACKET SOCK_RAW SOCK_RDM.

Here we only explain the first two:

SOCK_STREAM TCP Protocol socket.

  SOCK_DGRAM  UDP protocol socket.

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

Parameter 3: protocol protocol, options are:

    SOL_TCP:  TCP protocol.

    SOL_UDP:  UDPProtocol.

It can be seen from here that in fact, the second parameter and the third parameter of the socket_create function are related.

For example, if your first parameter uses the IPv4 protocol: AF_INET, Then, the second parameter applies to the TCP socket: SOCK_STREAM,

Then the third parameter must be SOL_TCP, should not be difficult to understand.

  TCP protocol socket, of course you can only use the TCP protocol, right? If you use UDP socket, then I won’t say how to choose the third parameter, haha, you know.

## Key function 2

  socket_connect($socketparameter1,$ipparameter2, $portParameter3)

## Function: Connect a socket, the return value is true or false

Parameter 1socket_createThe function return value

Parameters2ipAddress

Parameter 3: Port number

Key function 3

## socket_bind($socket parameter1,$ipparameter2,$portparameter3)

Function: Bind a socket, the return value is true or false

Parameter1socket_create function return value

## Parameter2ipAddress

## Parameter

3:Port number

Key function

4:   socket_listen($socket

parameter

1,$backlog parameter2)

Function: Listen to a socket, the return value is true or false

  Parameter1:The function return value of socket_create

Parameter 2: Maximum number of listening sockets

  Key functions5

  socket_accept($socket)

Function: Receive socket resource information, return the socket information resource successfully, failure is false

##   Parameter: socket_create Function return value

## Key function6

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

   Function: Read the resource information of the socket,

Return value: Successfully convert the socket resource into string information, failure is false

  Parameter 1: # The function return value of ##socket_create or socket_accept

Parameter 2: The length of the read string

Key function 7

  socket_write($socketparameter1$msgparameter2$strlenParameter3)

Function: Write data into the socket

Return value: Successfully returns the byte length of the string, failure is false

Parameter 1: socket_create or socket_accept function return value

  Parameter2: String

Parameter 3: The length of the string

Key function 8

##  socket_close($socket)

##   Function: Close the socket

Return value: Success returns true, failure returns false

Parameters: ## The function return value of #socket_create or socket_accept

These eight The function is the core function of

socket. Here are two more important functions socket_last_error($socket)

, the parameters are ## The return value of

#socket_create is used to obtain the last error code number of the socket. The return value is socketcode

  socket_strerror($code), the parameter is the return value of the socket_last_error function, get the code String information, the return value is the socket error message

These two functions are still very important in socket programming , when writing socket, I think you still have to use it, especially for novices, it can be used for debugging

  

##                                                                              ious me. Please pay attention. Please read my comments carefully. Comments are very important. Comments are very important. Comments are very important. Important. I have to shout three times, haha.

Server script, D:\vhost\test\socket\server_socket.php


Simple understanding of php socket programming##

<?php //创建服务端的socket套接流,net协议为IPv4,protocol协议为TCP$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);    /*绑定接收的套接流主机和端口,与客户端相对应*/
    if(socket_bind($socket,&#39;127.0.0.1&#39;,8888) == false){        echo &#39;server bind fail:&#39;.socket_strerror(socket_last_error());        /*这里的127.0.0.1是在本地主机测试,你如果有多台电脑,可以写IP地址*/
    }    //监听套接流
    if(socket_listen($socket,4)==false){        echo &#39;server listen fail:&#39;.socket_strerror(socket_last_error());
    }//让服务器无限获取客户端传过来的信息do{    /*接收客户端传过来的信息*/
    $accept_resource = socket_accept($socket);    /*socket_accept的作用就是接受socket_bind()所绑定的主机发过来的套接流*/

    if($accept_resource !== false){        /*读取客户端传过来的资源,并转化为字符串*/
        $string = socket_read($accept_resource,1024);        /*socket_read的作用就是读出socket_accept()的资源并把它转化为字符串*/

        echo &#39;server receive is :&#39;.$string.PHP_EOL;//PHP_EOL为php的换行预定义常量
        if($string != false){            $return_client = &#39;server receive is : &#39;.$string.PHP_EOL;            /*向socket_accept的套接流写入信息,也就是回馈信息给socket_bind()所绑定的主机客户端*/
            socket_write($accept_resource,$return_client,strlen($return_client));            /*socket_write的作用是向socket_create的套接流写入信息,或者向socket_accept的套接流写入信息*/
        }else{            echo &#39;socket_read is fail&#39;;
        }    /*socket_close的作用是关闭socket_create()或者socket_accept()所建立的套接流*/
        socket_close($accept_resource);
    }
}while(true);
socket_close($socket);
Copy after login

Simple understanding of php socket programming##   Tips: Please note that the execution order of the above three functions, socket_bind, socket_listen, and socket_accept, cannot be changed, that is to say

. socket_bind must be executed first, then socket_listen, and finally socket_accept.

    客户端脚本,D:\vhost\test\socket\client_socket.php

 


Simple understanding of php socket programming

<?php     //创建一个socket套接流
    $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);    /****************设置socket连接选项,这两个步骤你可以省略*************/
     //接收套接流的最大超时时间1秒,后面是微秒单位超时时间,设置为零,表示不管它
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));     //发送套接流的最大超时时间为6秒
    socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 6, "usec" => 0));    /****************设置socket连接选项,这两个步骤你可以省略*************/

    //连接服务端的套接流,这一步就是使客户端与服务器端的套接流建立联系
    if(socket_connect($socket,'127.0.0.1',8888) == false){        echo 'connect fail massege:'.socket_strerror(socket_last_error());
    }else{        $message = 'l love you 我爱你 socket';        //转为GBK编码,处理乱码问题,这要看你的编码情况而定,每个人的编码都不同
        $message = mb_convert_encoding($message,'GBK','UTF-8');        //向服务端写入字符串信息

        if(socket_write($socket,$message,strlen($message)) == false){            echo 'fail to write'.socket_strerror(socket_last_error());

        }else{            echo 'client write success'.PHP_EOL;            //读取服务端返回来的套接流信息
            while($callback = socket_read($socket,1024)){                echo 'server return message is:'.PHP_EOL.$callback;
            }
        }
    }
    socket_close($socket);//工作完毕,关闭套接流
Copy after login

Simple understanding of php socket programming

 

     怎么测试这两个脚本呢?

    首先打开windows的dos窗口,就是cmd黑窗口,然后,运行php D:\vhost\test\socket\server_socket.php,

    让服务端的的黑窗口持续运行的,

    其次,php的客户端脚本可以通过浏览器运行,也可以再开一个cmd黑窗口运行

    php D:\vhost\test\socket\client_socket.php

      在这里请注意:php这个运行命名必须加入windows的环境变量中,假如不知道怎么加,

    请进入php运行命令目录用绝对命令运行,也可以百度把php命令加入环境变量中

    这里是我的情况,你的文件地址可能和我不一样,请按照你的地址情况来操作,否则,后果自负,呵呵

    上面已经说过了,socket编程必须要有服务端才能交流,所以服务端的黑窗口是必须让它持续开着的。

 

Postscript added:

socket_set_option($socketparameter1 $level parameter2$optname parameter3$optval parameter4)

The function of this function is to set data flow options for the socket, and it is also a very important function.

Parameter 1: socket_create or socket_accept## The function return value of

# Parameters 2: SOL_SOCKET, it seems that only this option

parameter 3 is related to parameter 4 of,

Parameters3 can be: SO_REUSEADDR SO_RCVTIMEO S0_SNDTIMEO

Explain:

SO_REUSEADDR It allows the socket port to be used again immediately after it is released

Parameter3If this is the case, the parameter 4 can be true or false

SO_RCVTIMEO  is the maximum timeout of the socket’s receiving resource

##SO_SNDTIMEO  is the socket The maximum timeout time of the word sending resource

Parameter3If it is these two, then parameter4 is an array like thisarray('sec'=>1,'usec'=>500000)

## The maximum timeout time is set in the array, but one is in seconds and the other is in microseconds, and the effect is the same

Related recommendations:

##php socket communication content

The above is the detailed content of Simple understanding of php socket programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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