Can php implement socket communication

03-13-2023

This article mainly introduces the related knowledge of whether php can realize socket communication. The content is detailed and easy to understand, the operation is simple and fast, and has certain reference value. , Let's take a look at it together.


PHP can achieve socket communication, its implementation method: 1. Create socketsocket_create() on the client side; and request the server to connect socket_connect();; 2. In The server creates socketsocket_create(); and binds the IP and port number socket_bind();; 3. Read or write messages from the client through socket_wirte();socket_read.

1 Background introduction

Goal: I hope to build a server through socket TCP transmission. The function of this server is to accept connections from multiple clients and Complete their mutual correspondence. For example, client A and client B are connected to server S at the same time, client A sends a message to server S, and server S will forward A's message to B. Similarly, B's message can also be forwarded to A through S. In this way,realizes the mutual communication between client A and client B.
This time we only realize the connection and communication between the client and the server, and there is no forwarding function for writing to the server for the time being.

2 A brief introduction to TCP

2.1 TCP's three-way handshake

TCP's three-way handshake can ensure normal communication between the server and the client. The process of three-way handshake: As for the explanation of this process, you can click the link below to view it.
QQ截图20230313153256.jpg

2.2 IP and PORT

The server needs to have an IP, and a port number needs to be provided for TCP communication.
The customer service needs an IP, and a port number is also required for TCP communication.

Personal understanding: IP is an address, which can be understood as a house. When you need to establish communication, you must first know where the house is. Otherwise, where should we send the information? ?
PORT port, the port number can be understood as a door of this house, we need to specify a door to transmit messages through this door or receive messages from this door.

2.2 Brief communication process between client and server

2.2.1 Some related functions of php

Client:

  1. create socketsocket_create();

  2. Request a connection to the serversocket_connect();

  3. < li>
  4. Send message to server/accept server messagesocket_wirte(); / socket_read();

  5. Close socketsocket_close( );


Server:

  • Create socketsocket_create();

  • Bind IP and port numbersocket_bind();

  • Listen to IP and port number ( 0.0.0.0 means any IP)socket_listen();

  • blocking and waiting for the connection of the customer service endsocket_accept();

  • Read client messages/write messages to clientssocket_wirte(); / socket_read();

  • < p>Close socketsocket_close();

2.2.2 Brief communication process

  1. The server creates a socket and binds IP and PORT, then enters the listening state and waits for the client to initiate a connection.

  • The client creates a socket and connects to the specified server IP and PORT.

  • The server accepts the connection initiated by the client.

  • Both parties can send data to each other

  • Both parties close the socket.

ABCreate socketCreate socket, set to allow access to IP and PORTListen to a certain (or all) IP and a certain port, and enter the block waiting for the clientInitiate connet to the specified server IP/PORTAccept client A's connetThe connection has been establishedSend informationSend messageAfter the communication, A and B close the socket at the same timeAB

This is a brief communication process, as for loop sending or abnormal detection, it is some details.

3 Start to practice

3.1 PHP installation and environment configuration
  1. Install PHP. Here I installed XAMPP directly, and this software installed PHP for me by itself. If it is the first time to use the php language, you can install PHP directly from Baidu, or you can install XAMPP.

  2. System environment configuration. When running the program, I run it through cmd, so I need to configure the system environment variables. For the configuration process, please refer to: link: PHP environment variable configuration.

  3. Check if the php command can run. After completing steps 1 and 2, run cmd and execute the command php -v, and the version number of PHP will be displayed after the operation is completed.

3.2 Client program

3.2.1 Writing program

  1. Create a new folder socket, create a new text document under this folder and rename it client.php NOTE: My folder is built on the desktop

  2. Open client.php NOTE: If you don’t have a php editor, you can open client.php directly with Notepad

  3. Write the program NOTE: I will give the program directly here, and give notes, you can understand it in conjunction with the 2.2 communication process, if you have any questions, please leave a message

<?php
$PORT = Please enter the port number; //Please refer to the blog post for the port number: *3.2.2 Program Execution*. Set valid port:
$client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //create socket/parameter 1: represents IPV4/parameter 2: stream transmission/parameter 3: TCP/
$result = socket_connect ($client, "122.114.122.174", $PORT); //Send a connection request to the specified address/port, connectThe connection result is returned to the result
if($result == false){ //Here we simply respond to the connection result/for the convenience of Debug
echo "ERROR CONNECT\n";
die ();
} else {
echo "CONNECTED\n";
}
$data = "Hello World\n"; //Create the message to be sent
socket_write($client, $data); //Send the message out
socket_close($client); //Close the socket
?>

  1. After the program is written, you can copy it directly, or download it directly. NOTE: If the program runs directly, an error will be reported. We need to specify a port number. Please continue to the next section, how to run the program.

3.2.2 Program Execution

  1. Get Program. Through the previous section, we already have a simple customer service program, please click to download.

  2. Find valid ports. Because we don't have a server now, we need to use the server address and port provided by others for debugging.
    Operation steps:
    1. Click here to open the webpage
    2. Find at the bottom of the page: 122.114.122.174:xxxxx
    3. Replace the xxxxx part into the second line in the program and save
    Web page operation:

    Program operation:

  3. Open cmd. If you have not configured PHP environment variables, please check: 3.1 PHP Installation and Environment Configuration
  4. Execute the commandcd desktop/socket. The purpose is to go to the socket folder and fill in the relevant path according to your own folder location.

  5. Execute the client programphp client.php. At this time, if an error is reported PHP Fatalerror, please click to view the solution

    Finally, we can see that the information has been received in the webpage.
    NOTE: After executing the program, if CONNECTED is not printed, wait for a while and find that ERROR CONNET is returned. This is because our port number has expired (can only be used for 3 minutes), just return to the web page to refresh and modify it into the program. If it cannot run correctly, please leave a message!

3.3 Local server and customer service program

If you don’t want to type it yourself, please Click here to download and jump to: 3.3.3 Program Execution.

3.3.1 Write program/server

  1. Create a new folder socket (if any, Please ignore), create a new text document under this folder and rename it to server.php NOTE: My folder is built on the desktop

  2. Open server.php NOTE: If you don’t have a php editor, you can directly open server.php with notepad at this time

  3. writeProgram NOTE: I will give the program directly here, and give notes, you can understand it in conjunction with the 2.2 communication process, if you have any questions, please leave a message

<?php
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //Create socket/parameter explanation is the same as customer service end
socket_bind($server, "0.0.0.0", 12345); // Binding port and IP/0.0.0.0 means that any address is allowed to initiate a connection/12345 means that port number 12345 is allowed to connect
socket_listen($server); //Enter monitoring
$connection = socket_accept($server) ; //Accept request and establish connection
$data = socket_read($connection, 1024); //Accept data
echo $data; //Print data
socket_close($server);/ /close socket
?>

3.3.2 Write program/client

  1. Open the folder socket (the folder where server.php is located), Create a new text document under this folder and rename it to client.php (if any, please open and modify the program directly) NOTE: My folder is built on the desktop

  2. Open client.php NOTE: If you don’t have a php editor, you can open client.php directly with Notepad

  3. Write in the program NOTE: I will give the program directly here, and give notes. You can understand it in conjunction with the 2.2 communication process. If you have any questions, please leave a message


  4. <?php
    $PORT = 12345; //Match with server port
    $client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //Create socket/parameter 1 :Represents IPV4/parameter 2: stream transmission/parameter 3: TCP/
    $result = socket_connect($client, "127.0.0.1", $PORT); //Send a connection request to the specified address/port, the connection result Return to resule/127.0.0.1 refers to the local IP
    if($result == false){ //Here we simply respond to the connection result/for the convenience of Debug
    echo "ERROR CONNECT\n";
    die();
    } else {
    echo "CONNECTED\n";
    }
    $data = "Hello World\n"; //create to send The message
    socket_write($client, $data); //Send the message out
    socket_close($client); //Close the socket
    ?>
    < /p>3.3.3 Program Execution

    1. Get Program. Through the previous section, we already have a local customer service program and a server program, please click to download

    2. Open cmd. If you have not configured PHP environment variables, please check: 3.1

    3. execute commandcd desktop/socketcd desktop/socket code>. Note: This path needs to be filled in according to your actual situation. The direct download should be cd desktop/simple-socket-php/local-client-server. The main purpose is to find where server.php is located forFolder, fill in the corresponding path according to your own folder location.

    4. Execute the server programphp server.php. We found that cmd was stuck, and at this time we were waiting for the client to connect. If an error is reported at this time, PHP Fatal error, please check and click to view the solution (if you want to force the process to exit, press Ctrl+C)

    5. Open another cmd.

    6. Execute the commandcd desktop/socket. Note: This path needs to be filled in according to your actual situation. The direct download should be cd desktop/simple-socket-php/local-client-server. The main purpose is to find the location of client.php forFolder, fill in the corresponding path according to your own folder location.

    7. Execute the client programphp client.php. (If you want to force quit the process, press Ctrl+C)

      If the server does not respond, please press Ctrl+C to end the process, and follow the Execute the program sequentially (first execute server.php in one CMD, then execute client.php in another CMD).



Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us