search
HomeBackend DevelopmentPHP ProblemHow to understand php socket

How to understand php socket

Jan 23, 2020 pm 07:01 PM
phpsocket

How to understand php socket

What is a socket?

Socket is an abstraction layer between the application layer and the transport layer. It abstracts the complex operations of the TCP/IP layer into several simple interfaces for the application layer to call the implementation process in the network. Communication. Socket originated from UNIX. Under the UNIX idea that everything is a file, inter-process communication is named file descriptor. Socket is an implementation of the "open-read/write-close" mode. Server and client Each client maintains a "file". After the connection is established and opened, content can be written to the file for the other party to read or the other party's content can be read. The file is closed when the communication ends.

The picture shows the location of Socket:

How to understand php socket

Socket communication process

Socket ensures that communication between different computers communication, that is, network communication. For websites, the communication model is communication between the server and the client. A Socket object is established at both ends, and then data is transmitted through the Socket object. Usually the server is in an infinite loop, waiting for the client to connect.

Related learning video tutorial sharing: php video tutorial

The following picture is a connection-oriented TCP timing diagram:

How to understand php socket

Client process:

The client process is relatively simple, create a Socket, connect to the server, and connect the Socket to the remote host (note: only TCP has the concept of "connection", some Sockets such as UDP, ICMP and ARP do not have the concept of "connection"), send data, read response data, until the data exchange is completed, close the connection, and end the TCP conversation.

How to understand php socket

The send() method is also available here: the difference is that sendall() will try to send all data before returning, and returns None when successful, while send() returns to send The number of bytes, an exception will be thrown on failure.

Server-side process:

Let’s talk about the server-side process. The server first initializes the Socket, establishes a streaming socket, and communicates with the local machine address and port. Bind, then notify TCP that it is ready to receive connections, call accept() to block, and wait for a connection from the client. If the client establishes a connection with the server at this time, the client sends a data request, the server receives the request and processes the request, and then sends the response data to the client, and the client reads the data until the data exchange is completed. Finally, the connection is closed and the interaction ends.

How to understand php socket

When accept() is called, the Socket will enter the waiting state. When the client requests a connection, the method establishes the connection and returns to the server. accept() returns a tuple with two elements (conn, addr). The first element conn is the new Socket object through which the server must communicate with the client; the second element addr is the client's IP address and port. data = conn.recv(1024)

The next step is the processing phase, where the server and client communicate (transmit data) through send() and recv().

The server calls send() and sends information to the client in the form of a string. send() returns the number of characters sent.

The server calls recv() to receive information from the client. When calling recv() , the server must specify an integer that corresponds to the maximum amount of data that can be received with this method call. recv() will enter the blocked state when receiving data, and finally return a string to represent the received data. If the amount of data sent exceeds what recv() allows, the data will be truncated. The excess data will be buffered on the receiving end. When recv() is called in the future, the remaining bytes will continue to be read. If there is excess data, it will be deleted from the buffer (as well as the client may have sent since the last call to recv() any other data). When the transmission is completed, the server calls Socket's close() to close the connection.

Look at the Socket process from the perspective of TCP connection:

TCP three-way handshake Socket process:

How to understand php socket

1. After the server calls socket(), bind(), and listen() to complete the initialization, it calls accept() to block and wait;

2. The client Socket object calls connect() and sends a message to the server. SYN and blocking;

3. The server completes the first handshake, that is, sends SYN and ACK responses;

4. After the client receives the response sent by the server, connect() Return and then send an ACK to the server;

5. The server Socket object receives the client's third handshake ACK confirmation. At this time, the server returns from accept() to establish a connection.

The next step is for the connection objects at both ends to send and receive data to each other.

TCP Socket process of four waves:

How to understand php socket

1. An application process calls close() to actively close and send a FIN;

2. After receiving the FIN, the other end passively executes the shutdown and sends an ACK confirmation;

3. Afterwards, the application process that passively executes the shutdown calls close() to close the Socket and also sends a FIN;

4. The end that receives this FIN acknowledges it with ACK from the other end.

Summary:

The above code simply demonstrates the use of basic functions of Socket. In fact, no matter how complex the network program is, these basic functions will be used. The above server code will only process one client request before processing the next client request. Such a server has very weak processing capabilities. In practice, servers need to have concurrent processing capabilities. In order to achieve concurrent processing, the server needs to fork. A new process or thread handles the request.

Recommended related articles and tutorials: php tutorial

The above is the detailed content of How to understand php socket. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

MinGW - Minimalist GNU for Windows

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools