PHP socket programming is relatively difficult to understand. However, as long as we understand the relationship between several socket functions and the roles they play, it should not be difficult to understand. In the author’s opinion, socket programming , in fact, it is to establish a client and server of a network service, which is the same as the client and server of mysql. As long as you understand what the client and server of mysql are, you should be able to understand the following. Something to talk about.
Regarding the network protocols involved in socket programming, such as TCP, UDP, socket three-way handshake, etc., there are very detailed explanations of these network protocols on the Internet. I will not go into them here. I will only take a screenshot of the process of establishing a socket. Let you take a look:
This picture was stolen from others through hard work. You must take a good look at it. At the same time, I also express my gratitude to the author whose screenshot was stolen from me. I am very grateful to the author. 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 the socket establish a connection? As mentioned above, the process of establishing a connection is essentially the same as the connection between mysql client and server. The difference between it and mysql is that the server and client of mysql have been edited for us, we just need to apply it. However, the critical moment has come. Socket does not provide us with anything. The only thing it provides us is: dozens of socket functions.
The implication is that socket programming requires us to create the server and client ourselves. In other words, ``socket programming``--it requires us to build a server and client application similar to mysql.
Having said that, I want to ask, do you think this socket gives people a headache? It neither creates a server nor a client for us to apply. We have to use the socket function ourselves and create our own network protocol socket application. Doesn't this give you a headache? There is no solution to the headache. If you need your own application, you still have to deal with sockets. Haha, this is just a digression, I won’t say much more, let’s get to the point.
Before you are confused by socket programming, I will let you take a look at several key functions of socket and explain their respective functions to you first. Otherwise, if someone who has no foundation in socket programming reads this, I'm afraid that after reading it, you will decisively skip this article and develop a phobia about sockets from now on. Haha, say more.
Key function 1 of socket:
socket_create($net parameter 1, $stream parameter 2, $protocol parameter 3)
Function: Create a socket socket. To put it bluntly, it is a network data stream.
Return value: a socket, or false, an E_WARNING warning will be issued if the parameter is incorrect
The PHP online manual makes it more clear:
socket_create creates and returns 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.
Parameter 1 is: network protocol,
What are the network protocols? Its options are the following three: AF_INET: IPv4 network protocol. Both TCP and UDP can use this protocol. This is generally used, you know.
AF_INET6: IPv6 network protocol. Both TCP and UDP can use this protocol.
AF_UNIX: Local communication protocol. High-performance and low-cost IPC (Inter-Process Communication).
Parameter 2: Socket stream, options are:
SOCK_STREAM SOCK_DGRAM SOCK_SEQPACKET SOCK_RAW SOCK_RDM.
Only the first two are explained here:
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: UDP protocol.
It can be seen from here that the second parameter and the third parameter of the socket_create function are actually related.
For example, if your first parameter uses the IPv4 protocol: AF_INET, and then the second parameter uses the TCP socket: SOCK_STREAM,
then the third parameter must use SOL_TCP, which should not be difficult to understand.
As for TCP protocol sockets, of course you can only use TCP protocol, right? If you use UDP sockets, I won’t say how to choose the third parameter, haha, you know.
Key function 2:
socket_connect($socket parameter 1, $ip parameter 2, $port parameter 3)
Function: connect a socket, the return value is true or false
Parameter 1: function return of socket_create Value
� uff– in in in in inules
• Parameter 3: port number
• Key function 3:
• socket_bind($socket parameter 1, $ip parameter 2, $port parameter 3)
• Function: Bind a socket , the return value is true or false
Parameter 1: function return value of socket_create
Parameter 2: ip address
Parameter 3: Port number
Key function 4:
socket_listen($socket parameter 1, $backlog parameter 2 )
Function: monitor a socket, the return value is true or false
Parameter 1: function return value of socket_create
Parameter 2: Maximum number of listening sockets
Key function 5:
socket_accept($ socket)
Function: Receive socket resource information, return the socket information resource successfully, failure is false
Parameter: function return value of socket_create
Key function 6:
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 of socket_create or socket_accept Value
Parameter 2: The length of the read string
Key function 7:
socket_write($socket parameter 1, $msg parameter 2, $strlen parameter 3)
Function: Write data into the socket
Return value: Successfully returns the byte length of the string, failure is false
Parameter 1: Function return value of socket_create or socket_accept
Parameter 2: String
Parameter 3: String length
Key function 8 :
Socket_Close ($ Socket)
: Close Set Piece
Return Value: Successful return to TRUE, False
Parameter: Socket_create or Socket_accept. , two more important functions are listed below
socket_last_error($socket), the parameter is the return value of socket_create, its function is to obtain the last error code number of the socket, and the return value is the socket code
socket_strerror($code ), the parameter is the return value of the socket_last_error function, and the string information of the code is obtained. The return value is also the error message of the socket. These two functions are still very important in socket programming. When writing socket programming, I I think you still have to use it, especially for novices, it can be used for debugging
Up is the code. Pay attention, please read my comments carefully. Comments are very important, comments are very important, comments are very important, and important things are important. Shout three times, haha.
Server-side script, D:vhosttestsocketserver_socket.php
<?php //创建服务端的socket套接流,net协议为IPv4,protocol协议为TCP $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); /*绑定接收的套接流主机和端口,与客户端相对应*/ if(socket_bind($socket,'127.0.0.1',8888) == false){ echo 'server bind fail:'.socket_strerror(socket_last_error()); /*这里的127.0.0.1是在本地主机测试,你如果有多台电脑,可以写IP地址*/ } //监听套接流 if(socket_listen($socket,4)==false){ echo 'server listen fail:'.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 'server receive is :'.$string.PHP_EOL;//PHP_EOL为php的换行预定义常量 if($string != false){ $return_client = 'server receive is : '.$string.PHP_EOL; /*向socket_accept的套接流写入信息,也就是回馈信息给socket_bind()所绑定的主机客户端*/ socket_write($accept_resource,$return_client,strlen($return_client)); /*socket_write的作用是向socket_create的套接流写入信息,或者向socket_accept的套接流写入信息*/ }else{ echo 'socket_read is fail'; } /*socket_close的作用是关闭socket_create()或者socket_accept()所建立的套接流*/ socket_close($accept_resource); } }while(true); socket_close($socket);
Tips: Please note that the execution order of the three functions socket_bind, socket_listen, and socket_accept above cannot be changed, that is to say
socket_bind must be executed first, then socket_listen, and finally Only after executing socket_accept
Client script, D:vhosttestsocketclient_socket.php
<?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);//工作完毕,关闭套接流
D:vhosttestsocketclient_socket.php How to test these two scripts?
First open the Windows DOS window, which is the cmd black window, and then run php D:vhosttestsocketserver_socket.php,
Let the server-side black window continue to run,
Secondly, the PHP client script can be run through the browser , you can also open another cmd black window to run
php D:vhosttestsocketclient_socket.php
Please note here: the php running name must be added to the Windows environment variable. If you don’t know how to add it,
Please enter the php running command Run the directory with an absolute command, or you can add the php command to the environment variable in Baidu
This is my situation, your file address may be different from mine, please operate according to your address, otherwise, you will be responsible for the consequences, haha
As mentioned above, socket programming requires a server to communicate, so the black window on the server must be kept open.
Postscript:
socket_set_option($socket parameter 1, $level parameter 2, $optname parameter 3, $optval parameter 4)
The function of this function is to set the data flow option for the socket, which is still very important. function.
Parameter 1: The function return value of socket_create or socket_accept
Parameter 2: SOL_SOCKET, it seems that only this option
Parameter 3 is related to parameter 4,
Parameter 3 can be: SO_REUSEADDR SO_RCVTIMEO S0_SNDTIMEO
Explain it:
SO_REUSEADDR It is to allow the socket port to be used again immediately after it is released
If parameter 3 is this, then parameter 4 can be true or false
SO_RCVTIMEO It is the maximum timeout of the socket's receiving resources
SO_SNDTIMEO Is the maximum timeout of the socket's sending resource
If parameter 3 is these two, then parameter 4 is an array array like this ('sec'=>1,'usec'=>500000)
The maximum timeout time is set in the array, but one is in seconds and the other is in microseconds, the effect is the same

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools