Home  >  Article  >  Backend Development  >  Can php implement socket communication?

Can php implement socket communication?

藏色散人
藏色散人Original
2023-02-09 10:09:053572browse

php can implement socket communication. The implementation method is: 1. Create "socketsocket_create();" on the client and request a connection to the server "socket_connect();"; 2. Create "socketsocket_create()" on the server ;" and bind the IP and port number "socket_bind();"; 3. Read the client's message or write a message to the client through "socket_wirte();socket_read".

Can php implement socket communication?

The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer

Can php achieve socket communication?

socket PHP: Detailed and simple socket TCP communication PHP implementation

1 Background introduction

Goal: I hope to use socket The function of this server is to accept connections from multiple clients and complete their mutual communication. For example, client A and client B are connected to server S at the same time. Client A sends a message to server S. Server S will forward A's message to B. Similarly, B's message can also be forwarded to A through S. This realizes mutual communication between Client A and Client B.
This time we only implement the connection and communication between the client and the server, and do not have the forwarding function of 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 that the server and Clients can communicate normally. Three-way handshake process: As for the explanation of this process, you can click on the link below to view it.
Can php implement socket communication?
Reference: https://www.php.cn/link/70203474234c15a59de1eacc053f5690

##2.2 IP and PORT

The server needs to have one When communicating with IP or TCP, you also need to provide a port number.

The customer service side needs to have an IP, and when communicating with TCP, it also needs to provide a port number.

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 in this house. We need to specify a door to send messages in or receive messages from this door.

2.2 Brief communication process between client and server

2.2.1 Some related functions of php
Client:

    Create socket
  1. socket_create();
  2. Request a connection from the server
  3. socket_connect();
  4. Send a message to the server /Accept server messages
  5. socket_wirte(); / socket_read();
  6. Close socket
  7. socket_close();
Server:

  • Create socket

    socket_create();

  • Bind IP and port number

    socket_bind();

  • Listening IP and port number (0.0.0.0 means any IP)

    socket_listen();

  • Blocking and waiting for customer service End connection

    socket_accept();

  • Read client messages/write messages to clients

    socket_wirte(); / socket_read();

  • Close socket

    socket_close();

2.2.2 Brief communication process
    The server creates a socket, binds IP and PORT, and then enters the listening state to wait 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.

#AB ##Create socketCreate socket, set Allow access to IP and PORTListen to a certain (or all) IP and a certain port, and enter blocking waiting for the clientInitiate connet to the specified server IP/PORTAccept connet from client AThe two parties have established a connectionSend messageSend message##After the communication ends, A and B agree with Close the socketAB

This is a brief communication process. As for cyclic sending or abnormality detection, it is some details.

3 Start practicing

3.1 PHP installation and environment configuration

  1. Install PHP . Here I installed XAMPP directly, and this software installed PHP for me on its own. If this is your first time using 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 whether the php command can run. After completing steps 1 and 2, run cmd and execute the command php -v. After the operation is completed, the PHP version number will be displayed. Can php implement socket communication?

3.2 Client program

##3.2.1 Write program
    Create a new one Folder
  1. socket, create a new text document under this folder and rename it client.php NOTE: My folder is created on the desktop
  2. Open
  3. client.php NOTE: If you don’t usually have a php editor, you can directly open client.php with Notepad at this time
  4. write
  5. program NOTE: I will give the program directly here and give comments. You can understand it based on the 2.2 communication process. If you have any questions, please leave a message
  6. <?php
    $PORT = 请输入端口号; //端口号请查看博文:*3.2.2 程序执行*。设置有效端口:
    $client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //创建socket/参数1:代表IPV4/参数2:流传输/参数3:TCP/
    $result = socket_connect($client, "122.114.122.174", $PORT); //向指定地址/端口发出连接请求,连接结果返回到resule
    if($result == false){  //这里我们简单的对连接结果进行响应/为了Debug方便
        echo "ERROR CONNECT\n"; 
        die();
    } else {
        echo "CONNECTED\n";
    }
    $data = "Hello World\n"; //建立将要发送的消息
    socket_write($client, $data); //将消息发送出去
    socket_close($client); //关闭socket
    ?>
    After the program is written, you can copy it directly, or
  1. download it directly. NOTE: If the program is run directly, an error will be reported. We need to specify a port number. Please continue to the next section on 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 a valid port. 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 to the second line in the program and save
    Web page operation:

    Can php implement socket communication? Program operation:

    Can php implement socket communication?
  3. Open cmd. If the PHP environment variables are not configured, please see: 3.1 PHP installation and environment configuration
  4. Execute the command cd desktop/socket. The purpose is to go to the socket folder and fill in the relevant path according to the location of your own folder.
  5. Execute client programphp client.php. If a PHP Fatal error is reported at this time, please check Click to view the solution
    Can php implement socket communication? Finally, we can see that the information has been received in the web page.
    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 . If it cannot run correctly, please leave a message!

3.3 Local server and client program

If you don’t want to type it yourself, Pleaseclick here to download and jump to: 3.3.3 Program execution.

3.3.1 写程序/服务器
  1. 新建一个文件夹socket(如有,请忽略),在该文件夹下新建文本文档并改名为server.php NOTE:我的文件夹建在桌面上
  2. 打开server.php NOTE:如果你平时没有php的编辑器,这个时候可以直接用记事本打开server.php
  3. 写入程序 NOTE:程序我这里直接给出,并给予注释,大家可以结合2.2通信过程进行理解,如有疑问请留言
<?php
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //创建socket/参数解释同客服端
socket_bind($server, "0.0.0.0", 12345); //绑定端口和IP/0.0.0.0表示允许任意地址发起连接/12345表示允许12345端口号进行连接
socket_listen($server); //进入监听
$connection = socket_accept($server); //接受请求并建立连接
$data = socket_read($connection, 1024); //接受数据
echo $data; //打印数据
socket_close($server);//关闭socket
?>
3.3.2 写程序/客户端
  1. 打开文件夹socket(server.php所在文件夹),在该文件夹下新建文本文档并改名为client.php(如有,请打开直接修改程序即可) NOTE:我的文件夹建在桌面上
  2. 打开client.php NOTE:如果你平时没有php的编辑器,这个时候可以直接用记事本打开client.php
  3. 写入程序 NOTE:程序我这里直接给出,并给予注释,大家可以结合2.2通信过程进行理解,如有疑问请留言
<?php
$PORT = 12345; //与server端口匹配
$client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //创建socket/参数1:代表IPV4/参数2:流传输/参数3:TCP/
$result = socket_connect($client, "127.0.0.1", $PORT); //向指定地址/端口发出连接请求,连接结果返回到resule/127.0.0.1指本地IP
if($result == false){  //这里我们简单的对连接结果进行响应/为了Debug方便
    echo "ERROR CONNECT\n"; 
    die();
} else {
    echo "CONNECTED\n";
}
$data = "Hello World\n"; //建立将要发送的消息
socket_write($client, $data); //将消息发送出去
socket_close($client); //关闭socket
?>
3.3.3 程序执行
  1. 获取程序。通过上节,我们已经有一个本地客服端程序和一个服务器程序,下载请点击
  2. 打开cmd。如果没有配置PHP的环境变量请查看:3.1
  3. 执行命令cd desktop/socket。注意:这个路径需要根据自己实际情况填写,直接下载的应该是cd desktop/simple-socket-php/local-client-server主要目的是为了找到server.php所在的文件夹,根据自己文件夹位置填写相应路径。
  4. 执行服务器程序php server.php。我们发现cmd卡住了,这个时候在等待客户端连接进来。这个时候如果报错PHP Fatal error,请查看点击查看解决方法(如果想强制退出进程按下Ctrl+C
    Can php implement socket communication?
  5. 再打开一个cmd
  6. 执行命令cd desktop/socket。注意:这个路径需要根据自己实际情况填写,直接下载的应该是cd desktop/simple-socket-php/local-client-server主要目的是为了找到client.php所在的文件夹,根据自己文件夹位置填写相应路径。
  7. 执行客户端程序php client.php。(如果想强制退出进程按下Ctrl+C
    Can php implement socket communication?
    如果服务器没有反应,请按下Ctrl+C结束进程,重新按照顺序(先在一个CMD执行server.php,再在另一个CMD执行client.php)执行程序。如有疑问,请留言。

4 结束

到这里,我们已经实现了基本的socket通信,当然,这个程序是完全不能实际应用的,如果想要实际应用,需要增加很多细节方面的东西,有一个做的比较好的Workerman,大家可以自行搜索。
之后我会更新如何把这个server.php在自己的阿里云服务器上面运行,这样,我们就可以随时连接进去实现客服端的相互通信了。如果有兴趣可以关注等待。

推荐学习:《PHP视频教程

The above is the detailed content of Can php implement socket communication?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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