Home Backend Development PHP Tutorial Write basic Socket programs in PHP

Write basic Socket programs in PHP

Nov 18, 2019 pm 02:11 PM
php

Warning to young people

Utopias are useless. Personal ability comes from every day's hard work, rather than reaching the sky in one step. Don't be afraid of any new knowledge. One day, every drop of water will penetrate the stone. It will be dark and the flowers will be bright.

My purpose

Because in my future study, I may use network content, but at the same time, many coders who write PHP have never written sockets program, but I must have heard of it, and I must have heard of the word network programming, so for future learning, I plan to briefly explain the relevant knowledge here. This blog post comes with an example program, and the code is hosted on Code Cloud (php-socket-base-code: https://gitee.com/obamajs/php-socket-base-code), you only need to download it, configure the relevant environment, and follow the instructions to run it.

Environment configuration

Socket programming needs to enable the socket extension of php. The computer I use is windows, so here you only need to open the php.ini file and find this line Just remove the comments

extension=sockets
Copy after login

Official Document

The official address of php socket programming is: php socket (https://www.php.net/manual/ en/book.sockets.php)

Server-side programming

Socket programming follows certain programming steps. These steps are indispensable. Client and server Programming is different, let's look at the server first.

Write basic Socket programs in PHP

Create socket

Sockets are system resources. We first call the socket_create method (refer to the official documentation: https: //www.php.net/manual/en/function.socket-create.php), the call is as follows:

$this->socket_handle = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$this->socket_handle) {
      //创建失败抛出异常,socket_last_error获取最后一次socket操作错误码,socket_strerror打印出对应错误码所对应的可读性描述
     throw new Exception(socket_strerror(socket_last_error($this->socket_handle)));
} else {
          echo "create socket successful\n";
}
Copy after login

The first parameter specifies whether the current socket uses ipv4 or ipv6, if so If the former is the case, then pass AF_INET, otherwise AF_INET6. Of course, there is another type, which is AF_UNIX. This will not be discussed for the time being. We generally choose AF_INET (ipv6 is not very popular).

The second parameter specifies the type of protocol. Generally, TCP or UDP is selected. TCP is a reliable stream transmission (the most widely used in life, ensuring reliability and security), while UDP is not. , this parameter generally selects TCP.

The third one is SOL_TCP if you selected TCP before, otherwise it is SOL_UDP.

Binding address and port number

Because a host may have multiple IP addresses, you need to specify which one your socket is listening to. Commonly used The value is 127.0.0.1, or listening to all addresses 0.0.0.0. So someone here may not understand. What is the difference between 127.0.0.1 and 0.0.0.0? 127.0.0.1 is just a loopback address and can only be used for local access. To put it bluntly, you can use it yourself. Because this IP is not open to the outside world, no one can access this address, so if your server address is set to 127.0. 0.1, if others want to access, they can only go to shit.

0.0.0.0 is not strictly an IP address. It means that all the IP addresses of this machine are mine, haha.

Understood the above, let’s look at the code for this call

if (!socket_bind($this->socket_handle, $this->addr, $this->port)) {
         throw new Exception(socket_strerror(socket_last_error($this->socket_handle)));
    } else {
         echo "bind addr successful\n";
 }
Copy after login

Is it very simple? The first parameter is the result returned by socket_create, and the second parameter is the address. The above is already As mentioned, the third parameter is the port number.

Listening socket

After the above steps, we just created a socket and bound the port number and address to it, but what about the system? Do you know it's a listening socket? So, our work is not done yet, so we have to tell it. Don't tell me that you are in a good relationship with the system! ! !

if (!socket_listen($this->socket_handle, $this->back_log)) {
      throw new Exception(socket_strerror(socket_last_error($this->socket_handle)));
  } else {
      echo "socket  listen successful\n";
 }
Copy after login

The second parameter is worth explaining. Please listen to me in detail. For every process in the Linux system, the system maintains a queue of pending sockets (first in, first out). , it has to be said on a first-come, first-served basis), it takes time for the upper-level program to process the business logic, so just wait. So what is the size of this queue set to? Its value is the second parameter, so can I set it to a large value? Saonian, are you thinking too much? This value is different in different systems. Don’t say I’m fooling you. See below.

The maximum number passed to the backlog parameter highly depends on the underlying platform. On Linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.
Copy after login

You don’t have to care about the precise data of this value, it is meaningless.

Everything is ready, all we need is Dongfeng

After the above operation, we can start to accept connections from the client, and this function is even simpler

$client_socket_handle = socket_accept($this->socket_handle);
Copy after login

The return value of this function is also a socket handle, so you can read and write it. In the current example program, what we do is very simple, so simple that you can doubt your life.

 $client_socket_handle = socket_accept($this->socket_handle);
        if (!$client_socket_handle) {
            echo "socket_accept call failed\n";
            exit(1);
        } else {
            while (true) {
                $bytes_num = socket_recv($client_socket_handle, $buffer, 100, 0);
                if (!$bytes_num) {
                    echo "socket_recv  failed\n";
                    exit(1);
                } else {
                    echo "content from client:" . $buffer . "\n";
                }
            }
        }
Copy after login

Reading socket

Taking the above example, we use socket_recv to read the content from the client. This function is very simple, and the function prototype is as follows

socket_recv ( resource $socket , string &$buf , int $len , int $flags ) : int
Copy after login

The read content will be returned in the second parameter. The second parameter passes the number of characters we want to read. The fourth parameter can be directly set to 0. The return value of this function is the actual read value. The number of bytes taken.

Client Programming

客户端相对于服务端来说,就很简单了,流程如下

Write basic Socket programs in PHP

创建套接字前面已经讲过了,不再详述,客户端只需要连接服务器即可,函数为 socket_create,我们来看一哈在当前的例子中,我们是如何调用的。

if (!socket_connect($this->socket_handle, $this->server_addr, $this->server_port)) {
            echo socket_strerror(socket_last_error($this->socket_handle)) . "\n";
            exit(1);
        } else {
            while (true) {
                $data = fgets(STDIN);
                //如果用户输入quit,那么退出程序
                if (strcmp($data, "quit") == 0) {
                    break;
                }
                socket_write($this->socket_handle, $data);
            }
        }
Copy after login

该函数只需要指定服务器的地址和端口号即可,参数是不是很简单

练习实例

在讲解基本函数调用的时候,我就把自带程序的核心部分,复制出来了,如果要完整的程序,这里是地址(php-socket-base-code:https://gitee.com/obamajs/php-socket-base-code),代码非常简单,再次提醒,这些代码完全是用于给大家讲解基本的 socket 变成操作,为大家以后的学习打下基础,那么如何使用这个例子程序呢?

进入到命令行,开启服务器程序

php TcpServer.php,

打开另外一个命令行界面,

php TcpClient.php,

在客户端界面,输入任何文本,再输入回车,再切换到服务器界面,您将会看到客户端输入的内容

在笔者的电脑上操作实例截图如下:

Write basic Socket programs in PHP

The above is the detailed content of Write basic Socket programs in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles