


A brief introduction to the socket communication principle of PHP
You are not familiar with the words TCP/IP, UDP, Socketprogramming, right? With the development of network technology, these words are flooding our ears. So I want to ask:
1. What are TCP/IP, UDP?
2. Where is Socket?
3. What is Socket?
4. Will you use them?
What are TCP/IP, UDP?
TCP/IP (Transmission Control Protocol/Internet Protocol) ) designed. UDP (User Data Protocol
, User Datagram Protocol) is the protocol corresponding to TCP. It is a member of the TCP/IP protocol family.表 There is a picture here that shows the relationship between these protocols. The TCP/IP protocol suite includes the transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP. Where is the Socket? In Figure 1, we don’t see the shadow of Socket, so where is it? Let’s let pictures speak for themselves.
It turns out that the Socket is here. What is Socket?
Can you use them? Predecessors have done a lot for us, and communication between networks has become much simpler, but after all, there is still a lot of work to be done. When I heard about Socket programming before, I thought it was relatively advanced programming knowledge, but as long as we understand the working principle of Socket programming, the mystery will be lifted. A scene from life. If you want to call a friend, dial the number first. The friend will pick up the phone after hearing the ringing tone. At this time, you and your friend will be connected and you can talk. When the communication is over, hang up the phone to end the conversation. Scenes in life explain how this works. Maybe the TCP/IP protocol family was born in life, but this is not necessarily the case.
Let’s start with the server side. The server first initializes the Socket, then binds to the port, listens to the port, calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection, and the interaction ends. socket related functions: Case 1: Socket communication demonstration Server side: This is the server-side code of the socket. Then run cmd, pay attention to the storage path of your own program. No reflection, now the server program has started running and the port has started listening. Run netstat -ano to check the port status. Mine is port 1935
Look, the port is already in the LISTENING state. Next we only need to run the client program to connect. Up code Now the client has connected to the server. Case 2: Detailed code explanation // Set some basic variables $host = $port [Copy to clipboard] PHP CODE: set_time_limit( The first parameter "AF_INET" is used to specify the domain name; [Copy to clipboard] 4. Once a Socket handle is created, the next step is to specify or bind it to the specified Website construction companyaddress and Enterprise website constructionport. This can be done through the socket_bind() function. [Copy to clipboard] 5. After the Socket is created and bound to a port, you can start listening for external connections. . PHP allows you to start a website production company listening through the socket_listen() function, and you can specify a number (in this example, the second parameter: 3) [Copy to clipboard] 6. Until now, your server has basically done nothing except waiting for the connection request from the client. .Once a client connection is received, the socket_accept() function comes into play. It receives the connection request and calls another sub-Socket to handle the client-website productioninformation between servers. [Copy to clipboard] This sub-socket can now be used by subsequent Webpage Used to make client-server communication. $input = $spawn
------------------------------------------------- -------------------------------------------------- -
socket_accept() Accept a Socket connection
socket_bind() Bind the socket to an IP address and port
socket_clear_error() Clear the socket error or last error code
socket_close() Close a socket resource
socket_connect() Start A socket connection
socket_create_listen() opens a socket listening on the specified port
socket_create_pair() generates a pair of undifferentiated sockets into an array
socket_create() generates a socket, which is equivalent to generating a socket data structure
socket_get_option() obtains Socket options
socket_getpeername() Get the ip address of a remote similar host
socket_getsockname() Get the ip address of the local socket
socket_iovec_add() Add a new vector to a scatter/aggregate array
socket_iovec_alloc() This function creates a socket that can send and receive Read and write iovec data structure
socket_iovec_delete() Delete an allocated iovec
socket_iovec_fetch() Return the data of the specified iovec resource
socket_iovec_free() Release an iovec resource
socket_iovec_set() Set the new value of iovec data
socket_last_error() Get The last error code of the current socket
socket_listen() listens to all connections from the specified socket
socket_read() reads the data of the specified length
socket_readv() reads the data from the scatter/aggregate array
socket_recv() ends the data from the socket To the cache
socket_recvfrom() accepts data from the specified socket, if not specified, the current socket is defaulted
socket_recvmsg() Receives messages from iovec
socket_select() Multiple selection
socket_send() This function sends data to the connected socket
socket_sendmsg() Send a message to the socket
socket_sendto() Send a message to the socket at the specified address
socket_set_block() Set the socket to block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() Set the socket option
socket_shutdown( ) This function allows you to close reading, writing, or the specified socket
socket_strerror() returns the detailed error with the specified error number
socket_write() writes data to the socket cache
socket_writev() writes data to the scatter/aggregate array<span><?php
//确保在连接客户端时不会超时
set_time_limit(0);
$ip = '127.0.0.1';
$port = 1935;
/*
+-------------------------------
* @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() 失败的原因是:".socket_strerror($sock)."\n";
}
if(($ret = socket_bind($sock,$ip,$port)) < 0) {
echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";
}
if(($ret = socket_listen($sock,4)) < 0) {
echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";
}
$count = 0;
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
break;
} else {
//发到客户端
$msg ="测试成功!\n";
socket_write($msgsock, $msg, strlen($msg));
echo "测试成功了啊\n";
$buf = socket_read($msgsock,8192);
$talkback = "收到的信息:$buf\n";
echo $talkback;
if(++$count >= 5){
break;
};
}
//echo $buf;
socket_close($msgsock);
} while (true);
socket_close($sock);
?></span>
<span><?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";
$port = 1935;
$ip = "127.0.0.1";
/*
+-------------------------------
* @socket连接整个过程
+-------------------------------
* @socket_create
* @socket_connect
* @socket_write
* @socket_read
* @socket_close
+--------------------------------
*/
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}else {
echo "OK.\n";
}
echo "试图连接 '$ip' 端口 '$port'...\n";
$result = socket_connect($socket, $ip, $port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
echo "连接OK\n";
}
$in = "Ho\r\n";
$in .= "first blood\r\n";
$out = '';
if(!socket_write($socket, $in, strlen($in))) {
echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
}else {
echo "发送到服务器信息成功!\n";
echo "发送的内容为:<font color='red'>$in</font> <br>";
}
while($out = socket_read($socket, 8192)) {
echo "接收服务器回传信息成功!\n";
echo "接受的内容为:",$out;
}
echo "关闭SOCKET...\n";
socket_close($socket);
echo "关闭OK\n";
?></span>
$host = "192.168.1.99";
$port = 1234 ;
/ / Set timeout
set_time_limit(0);
// Create a Socket
$socket = socket_create (AF_INET, SOCK_STREAM, 0) or die("Could not createocketn");
//Bind Socket to port
$result = socket_bind( $socket, $host, $port) or die("Could not bind tosocketn");
// Start monitoring the link
$ result = socket_listen($socket, 3) or die("Could not set up socketlistenern");
// accept incoming connections
// Another Socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incomingconnectionn");
/ / Get input from the client
$input = socket_read($spawn, 1024) or die("Could not read inputn" );
//Clear the input string
$input =trim($input);
//Process client input and return the result
$output = strrev($input) . , $output,
strlen ($output)) or die("Could not writeoutputn");//Close socketssocket_close( $spawn
);socket_close
($socket);The following is a detailed description of each step:For example:
website design company,design company , Internet marketing,
Internet promotion,Internet optimizationwebsite promotion,website optimization,website operation, etc. are all produced similarly. steps. 1. The first step is to create two variables to save the IP address and port of the server where the Socket is running. You can set it as your own website designserver and building websiteport ( This port can be a number between 1 and 65535), provided that this port is not in use.
[Copy to clipboard]PHP CODE:"192.168.1.99";
<span>= <br></span>1234<span></span>;<span></span><span></span> <span><br></span><span></span>2. You can use set_time_out on the server side ()<span></span> function<span></span> to ensure that PHP will not time out while waiting for the client to connect.<span></span><br>
Building a website0);
<span><br></span><span>3. Based on the previous, it’s time to use sock et_creat() function creates A Socket - This function returns a Socket handle, which will be used in all future functions for building websites.<h5 id="span-PHP-CODE-span"><span>PHP CODE:</span></h5>
<p><span><code><span>//Create Socket<br></span><span>$socket </span><span>= </span><span>socket_create</span><span>(</span><span>AF_INET</span><span>, </span><span>SOCK_STREAM</span><span>, </span><span>0</span><span>) or die( </span><span>"Could not create<br>socketn"</span><span>);</span><br>
The second parameter "SOCK_STREM" tells the function what to create class type Socket (in this case TCP class type)
So, if you want to create a UDP Socket, you can use the following code: PHP CODE:
<span>// Create socket<br></span><span>$socket </span><span>= </span><span>socket_create</span><span>(</span> <span>AF_INET</span><span>, </span><span>SOCK_DGRAM</span><span>, </span> <span>0</span><span>) or die(</span><span>"Could not create<br>socketn"</span><span>);</span><br>
PHP CODE:
<span>// Bind socket to specified address and port <br></span><span>$result </span><span>= </span><span>socket_bind</span><span>(</span><span>$socket</span><span>, </span> <span>$host</span><span>, </span><span>$port </span><span>) or die(</span><span>"Could not bind to<br>socketn"</span><span>);</span><br>
PHP CODE:
<span>// Start listening for connections<br></span><span>$result </span><span>= </span><span>socket_listen</span><span>(</span> <span>$socket</span><span>, </span><span>3</span> <span>) or die(</span><span>"Could not set up socket<br>listenern"</span><span>);</span><br>
PHP CODE:
<span>//Accept request link<br>// Call subsocket to process information<br></span><span>$spawn </span> <span>= </span><span>socket_accept</span> <span>(</span><span>$socket</span><span>) or die(</span><span>"Could not accept incoming<br>connectionn"</span><span>);</span><br>
7. When a connection is established, the server will wait for the client to send some Input information. This information can be obtained by the socket_read() function and assigned to the $input variable of PHP.[Copy to clipboard]PHP CODE: socket_read(
, <span><br>1024</span><span>) or die(</span><span>"Could not read inputn"</span><span>) ;</span>?&<span></span>gt<span></span>;<span></span><span></span><span>The second parameter of <p><span><span><span>socker_read is used to specify the number of bytes to be read. You can use it to limit the size of </span><span>data</span><span> obtained from the client. </span><br><span>Note: The socket_read function will always read the shell The client <span>APP</span><span> develops </span>data until it meets n,t or
</span>
The above has introduced a brief introduction to the socket communication principle of PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials. <br>
<span>
<span></span></span></span></span></p></span>

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using
