


PHP+Socket series realizes data transmission between client and server
This article brings you relevant knowledge about php socket. It mainly introduces what is socket? How does php socket realize client-server data transmission? Friends who are interested can take a look below. I hope it will be helpful to everyone.
Socket introduction
To achieve communication between network processes, almost all applications use sockets. Sockets are the intermediate communication between the application layer and the TCP/IP protocol family. Abstraction layer, which is a set of interfaces. In the design mode, socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the socket interface. For the user, a set of simple interfaces is all, allowing the socket to organize the data to comply with the specified Protocol
The original meaning of socket in English is "hole" or "socket". It is also commonly called "socket" and is used to describe IP addresses and ports. It is a The handle of the communication chain can be used to implement communication between different virtual machines or different computers.
Three processes of socket link
Server listening: IP port number
Client request: Send to service End IP and port connection request
Link confirmation: The server socket listens or receives the client socket connection request, and it will create a new process. Send the server's socket description to the client in response to the client's request. Once the client confirms this description, the connection is established. The server's socket continues to be in the listening state and continues to accept connection requests from other client sockets.
php implements socket
If you need to use socket in php, you need to add -- when compiling php enable-sockets
configuration item to enable, you can use the php -m|grep sockets
command to check the enabling status. For the specific compilation process, please refer to this article
Quick Experience
The simplified codes for the server and client are as follows. After running, the server will block and wait for the client to connect. The client will ask for input content on the console. After input, the information will be displayed in the service The client prints, and the client displays the content converted to uppercase. This example server and client run on the same server:
Server listening
<?php // 创建套接字 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 设置 ip 被释放后立即可使用 socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, true); // 绑定ip与端口 socket_bind($socket, 0, 8888); // 开始监听 socket_listen($socket); while (true) { // 接收内容 $conn_sock = socket_accept($socket); socket_getpeername($conn_sock, $ip, $port); // echo '请求ip: ' . $ip . PHP_EOL . '端口: ' . $port; while (true) { // 获取消息内容 $msg = socket_read($conn_sock, 10240); // TODO 处理业务逻辑 // 将信息转为大写并原样返回客户端 socket_write($conn_sock, strtoupper($msg)); echo $msg; } }
Client connection
<?php // 创建套接字 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 连接服务端 socket_connect($socket, '127.0.0.1', 8888); while (true) { // 让控制台输入内容 fwrite(STDOUT, '请输入内容:'); $in = fgets(STDIN); // 向服务端发送内容 socket_write($socket, $in); // 读取服务端发送的消息 $msg = socket_read($socket, 10240); echo $msg; }
Syntax explanation
socket_create
socket_create(int $domain,int $type, int $protocol): resource|false
Create and return a socket resource , also usually called a communication node. A typical socket consists of at least 2 sockets, one running on the client side and one running on the server side.
Parameters:
-
##domain
Specifies what protocol the current socket uses. The available protocols are as follows:
Domain Description AF_INET IPv4 network protocol, both TCP and UDP are available Use this protocol AF_INET6 IPv6 network protocol, both TCP and UDP can use this protocol AF_UNIX - ##type
User specifies the current set Type used by the interface
type
Description Sequential, reliable, full-duplex, link-based byte stream, supporting data transfer flow control mechanism. The TCP protocol is based on this streaming socket. Support for data messages (connectionless, unreliable, fixed maximum length) UDP protocol is based on this message socket Sequential, reliable, full-duplex, connection-oriented, fixed maximum length data communication, the data end reads the entire data segment by receiving each data segment Packet Read the original network protocol. This special socket can be used to manually build any type of protocol. Generally, this socket is used To implement ICMP request Reliable data layer, but the arrival order is not guaranteed. General operating systems do not implement this function protocol
设置指定 domain 套接字下的具体协议,如果所需协议是 TCP 或者 UDP,可以直接使用常量SOL_TCP
或SOL_UDP
,这个参数的具体值可通过getprotobyname()
函数获取返回值
socket_create()
正确时返回一个套接字资源,失败时返回false
。可以调用socket_last_error()
获取错误码,错误码可以通过socket_strerror(int $err_no)
转换为文字的错误说明。socket_bind
socket_bind(resource $socket, string $address [, int $port]): bool
绑定一个地址与端口到套接字
参数:
socket
使用socket_create()
创建的套接字资源-
address
如果套接字是
AF_INET
族,那么address
必须是一个四点法的 IP 地址,例如127.0.0.1
、0.0.0.0
如果套接字是
AF_UNIX
族,那么address
是 Unix 套接字一部分(例如/tmp/my.sock
) -
port
(可选)该参数仅用于使用
AF_INET
族时,指定当前套接字监听的端口号
返回值:
绑定成功返回
true
,失败时则返回false
,同socket_create
,在绑定失败时可以调用socket_last_error()
获取错误码,错误码可以通过socket_strerror(int $err_no)
转换为文字的错误说明。socket_listen
socket_listen(resource $socket [, int $backlog]): bool
在使用
socket_create()
创建套接字并使用socket_bind()
将其绑定到名称之后,可能会告诉它侦听套接字上的传入连接。该函数仅适用于SOCK_STREAM
或SOCK_SEQPACKET
类型的套接字。参数:
-
socket
使用socket_create()
创建的套接字资源 -
backlog
最大数量的积压传入连接将排队等待处理,如果连接请求到达时队列已满,则客户端可能会收到指示为ECONNREFUSED
的错误。或者,如果底层协议支持重传,则可能会忽略该请求,以便重试可能会成功。
返回值:
绑定成功返回
true
,失败时则返回false
,可以调用socket_last_error()
获取错误码,错误码可以通过socket_strerror(int $err_no)
转换为文字的错误说明。socket_accept
socket_accept(resource $socket): resource|false
当有新的客户端连接时,返回一个新的 socket 资源以用于与客户端通信,如有多个连接排队,则返回第一个连接,相反如果没有待处理的连接,该函数会默认阻塞当前进程,直至新的客户端连接、断开
参数:
-
socket
使用socket_create()
创建的套接字资源
返回值:
成功时返回一个新的套接字资源,错误时返回
false
,可以调用socket_last_error()
获取错误码,错误码可以通过socket_strerror(int $err_no)
转换为文字的错误说明。socket_connect
socket_connect(resource $socket, string $address [, int $port = null]): bool
使用套接字实例发起到
address
的连接参数:
socket
该参数必须是由socket_create()
创建的socket
实例-
address
如果套接字是
AF_INET
族,那么address
必须是一个四点法的 IP 地址,例如127.0.0.1
如果支持 IPv6 并且套接字是AF_INET6
,那么address
也可以是一个有效的 IPv6 地址(例如::1
)如果套接字是
AF_UNIX
族,那么address
是 Unix 套接字一部分(例如/tmp/my.sock
)
返回值:
成功时返回
true
, 或者在失败时返回false
socket_write
socket_write(resource $socket, string $data [, int $length = null]): int|false
传输数据至指定套接字
参数:
socket
使用socket_create()
或socket_accept()
创建的套接字资源data
要发送的内容-
length
(可选)可以指定发送套接字的替代字节长度。如果这个长度大于实际发送内容的长度,它将被静默地截断为实际发送内容的长度。
返回值:
成功时返回成功发送的字节数,或者在失败时返回
false
,可以调用socket_last_error()
与socket_strerror(int $err_no)
获取具体错误信息socket_read
socket_read(resource $socket, int $length, int $mode = PHP_BINARY_READ): string|false
从套接字资源内读取数据
参数:
socket
使用socket_create()
或socket_accept()
创建的套接字资源(服务端为socket_accept()
客户端为socket_create()
)length
指定最大能够读取的字节数。否则您可以使用\r
、\n
、\0
结束读取(根据mode
参数设置)-
mode
(可选)PHP_BINARY_READ
(默认)- 使用系统的recv()
函数。二进制安全地读取数据。PHP_NORMAL_READ
- 读取到\n
、\r
时停止。
返回值:
socket_read()
返回一个字符串,表示接收到的数据。如果发生了错误(包括远程主机关闭了连接),则返回false
,可以调用socket_last_error()
与socket_strerror(int $err_no)
获取具体错误信息socket_close
socket_close(resource $socket): void
关闭并销毁一个套接字资源
参数:
-
socket
使用socket_create()
或socket_accept()
创建的套接字资源
返回值:
无
推荐学习:《PHP视频教程》
The above is the detailed content of PHP+Socket series realizes data transmission between client and server. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

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.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software