Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of swoole?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the knowledge points of swoole". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the knowledge points of swoole"?

Process explanation of swoole chat room

The whole chat room process is as follows:

-the user is authorized to log in to the http interface

-obtain the list of friends, the last unread message and the number of unread messages of different friends through the authorization request http API (for home page display)

-obtain the group list through authorization request (group messages are not read unread in order to save storage space)

-establish a ws link

-registers the disconnection reconnection mechanism to reconnect the ws when the close event is triggered

-set up a ping timer and ping every 30 seconds

-all unread messages are obtained through the ws interface, processed by the client, pushed to the notification bar, etc.

-receive a new message push and display it to the message list

-when you click into a group / friend message interface, you will automatically get the latest n messages, and when you pull up, you will continue to get n messages.

Line mode cgi protocol mode

Cgi mode Universal Gateway Interface (Common Gateway Interface), which allows web servers to communicate with applications through specific protocols, based on something like this:

User request-> Web server receives request-> Fork child process

Calling program / executor-> program returns content / program call ends-> web server receives content-> returns to the user

Because every time a user requests, the fork creation process calls the program once, and then destroys the process, so the performance is low.

Fast-cgi protocol mode

Fast-cgi is an upgraded version of cgi mode. It is like a resident cgi. As long as it is enabled, the request can be processed all the time, and the process no longer needs to be terminated. The principle of calling is roughly as follows:

Web Server fast-cgi process Manager initialization-> pre-fork n processes

User request-> web server receives request-> to fast-cgi process manager-> fast-cgi process management area to receive, to one of the idle fast-cgi processes-> processing completed, fast-cgi process becomes idle, waiting for next request-> web server to receive content-> return to user module mode

Module mode

When apache+php runs, the module mode is used by default. It starts php as a module of apache when apache starts. When it receives a user request, it directly processes it by calling the mod_php module. The details can be done by Baidu itself.

Php-cli mode

Php-cli mode belongs to the command line mode, which is the most unfamiliar running mode for many developers who start to learn php and start wamp,wnmp.

In this mode, php code can be executed by directly entering php xx.php without the help of other programs.

The command line mode is obviously different from the regular web mode:

* No timeout

* buffer buffering is turned off by default

* STDIN and STDOUT standard input / output / incorrect use

* output such as echo var_dump,phpinfo is output directly to the console

* different classes / functions are available

* different configurations of php.ini

Php-fpm

PHP-FPM (FastCGI process Manager) is used to replace most of the additional features of PHP FastCGI and is very useful for high-load websites.

Its functions include:

Advanced process management features that support smooth stop / start

Can work in different uid/gid/chroot environments and listen to different ports and use different php.ini profiles (instead of safe_mode settings)

Stdout and stderr logging

Be able to restart and cache the corrupted opcode in the event of an accident

Optimization support for file upload

"slow log"-recording the unusually slow running of scripts (recording not only file names, but also PHP backtrace information, which can be read and analyzed by using ptrace or similar tools for running remote processes)

Fastcgi_finish_request ()-Special function: used to continue time-consuming work in the background (input video conversion, statistical processing, etc.) after the request is completed and refreshed.

Dynamic / static subprocess generation

Basic SAPI running status information (Apache-like mod_status)

Php.ini-based configuration file.

How it works:

It works roughly as follows:

Php-fpm start-> generate n fast-cgi protocol processing processes-> listen for a port waiting task

User request-> web server receives request-> request is forwarded to php-fpm- > php-fpm to an idle process for processing

-> process completed-> php-fpm returned to web server-> web server received data-> returned to user

Network protocol

Network protocol A set of rules, standards, or conventions established for the exchange of data in a computer network. All network devices such as computers / mobile phones must follow the network protocol.

According to the steps of communication, the network protocol is divided into seven levels, from top to bottom:

Application layer

Presentation layer

Session layer

Transport layer

Network layer

Data link layer

Physical layer

Ip protocol (network layer)

Ip protocol is the basic protocol of the Internet, and it is the most popular network protocol at present.

Range

The responsibility of IP is to transfer data from source to destination. It is not responsible for ensuring transmission reliability, flow control, packet ordering and other services that are common to host-to-host protocols.

Interface

This protocol is invoked by the host-to-host protocol, which invokes the local network protocol to deliver the packet to the following gateway or destination host. For example, TCP can call the IP protocol, send the destination address and source address as parameters, and IP forms a packet and calls the local network (protocol) interface to send the packet.

Operation

IP implements two basic functions: addressing and segmentation. IP can send packets to the destination address according to the destination address included in the packet header, during which IP is responsible for choosing the path of transmission, which is called the routing function. If only small packets can be sent within some networks, IP can reassemble the packets and mark them in the header domain. These basic functions are included in the IP module, which exists on every host and gateway in the network, and these modules (especially on the gateway) have routing and other service functions. For IP, there is no connection between packets, and it is difficult for IP to say what connection or logical link.

IP uses four key technologies to provide services: service type, time to live, options, and header parity codes. The type of service refers to the desired quality of service. A service type is a set of parameters that represent the services that Internet can provide. This service type is used by gateways to select the actual transport parameters on a specific network, or on the next network to pass through, or on the next gateway to route this packet. Lifetime is the upper limit of how long a packet can survive. It is set by the sender and handled by the routed place. If the time to live is zero when it does not arrive, discard this packet. Options are important for control functions, but they are not necessary for normal communication. Options include timestamp, security, and special routing. The header check code ensures the correct transmission of data. If there is a verification error, discard the entire packet.

Ip address

When transferring data from source to destination, you need an ip address to transmit. Now ip addresses are divided into ipv4 and ipv6 addresses. Now the most common address is ipv4 address, such as 127.0.0.1 (local address) 119.75.217.109 (Baidu ip).

Ip transmission must have a clear ip address before data can be sent.

Tcp (Transport layer)

TCP (Transmission Control Protocol Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol defined by RFC 793of IETF. In the simplified computer network OSI model, it performs the functions specified by the fourth transport layer, and the user Datagram Protocol (UDP) is another important transport protocol in the same layer. In the Internet Protocol Family (Internet protocol suite), the TCP layer is the middle layer above the IP layer and below the application layer. Reliable, pipe-like connections are often needed between the application layers of different hosts, but the IP layer does not provide such a flow mechanism, but provides unreliable packet exchange.

The application layer sends an 8-bit byte data stream to the TCP layer for internetwork transmission, and the TCP then divides the data flow into message segments of appropriate length (usually limited by the maximum transmission unit (MTU) of the data link layer of the network to which the computer is connected). The TCP then passes the resulting packet to the IP layer, which transmits the packet over the network to the TCP layer of the receiving entity. In order to ensure that packet loss does not occur, TCP gives each packet a sequence number, which also ensures the sequential reception of packets transmitted to the receiving entity. Then the receiver entity sends back a corresponding acknowledgment (ACK) to the packet that has been successfully received; if the sender entity does not receive the acknowledgement within a reasonable round-trip delay (RTT), then the corresponding packet is assumed to have been lost and will be retransmitted. TCP uses a checksum function to check for errors in the data; a checksum is calculated both when sending and receiving.

Three-way handshake

TCP is the transport layer protocol in the Internet, which uses the three-way handshake protocol to establish a connection. When the active party sends out the SYN connection request, it waits for the other party to answer the SYN+ACK, and finally performs the ACK confirmation to the other party's SYN. This method of establishing a connection prevents incorrect connections, and the flow control protocol used by TCP is a variable-size sliding window protocol. The process of the TCP three-way handshake is as follows:

The client sends a SYN (SEQ=x) message to the server and enters the SYN_SEND state.

The server receives the SYN message, responds to a SYN (SEQ=y) ACK (ACK=x+1) message, and enters the SYN_RECV state.

The client receives the SYN message from the server, responds to an ACK (ACK=y+1) message, and enters the Established state.

Connected successfully

After a successful connection, the two parties can transmit the byte stream to each other, and the connection can be closed at any time. The transmitted data has the following characteristics.

The transmitted data is divided by tcp into the most suitable data blocks for transmission to the ip protocol, which is called a message segment or segment.

As a reliable connection, tcp starts a timer every time it sends a data segment, and sends an acknowledgement every time it receives the data segment. If the timer does not receive the acknowledgement in time, it will retransmit the data.

TCP will maintain its header and data verification and. This is an end-to-end checksum designed to detect any changes in the data during transmission. If there is an error in the check of the received segment, TCP will discard the message segment and do not acknowledge the receipt of the message segment (hopefully the sender timed out and resent it).

A stream of bytes consisting of two applications exchanging 8bit bytes over a TCP connection. TCP does not insert record identifiers in the byte stream. We call this the byte streaming service (bytestreamservice). If one side's application passes 10 bytes, then 20 bytes, and then 50 bytes, the other side of the connection will not know how many bytes the sender has sent each time. TCP receivers will charge as much as they have as long as their receive cache is not full. One end streams the bytes to the TCP connection, and the same byte stream appears on the other end of the TCP connection.

Waving four times

Establishing a connection requires three handshakes, while terminating a connection takes four waves, which is caused by the half-close of TCP. The specific process is shown below.

An application process first calls close, saying that the end performs an "active shutdown" (active close). The TCP on this end then sends a FIN section, indicating that the data has been sent.

The peer that receives the FIN performs a "passive shutdown" (passive close), and the FIN is confirmed by the TCP.

Note: the reception of FIN is also passed to the receiving application process as a file Terminator (end-of-file), after any other data that has been queued for the application process to receive, because the reception of FIN means that the receiving application process has no additional data to receive on the corresponding connection.

After a while, the application process that receives this file Terminator will call close to close its socket. This causes its TCP to send a FIN as well.

The original sender TCP that receives the final FIN (that is, the end that performs the active shutdown) confirms the FIN. Since you need a FIN and an ACK in each direction, you usually need four sections.

"usually" means that in some cases, the FIN of step 1 is sent with the data, and in addition, the sections sent in steps 2 and 3 are from the side that performs the passive shutdown and may be merged into one section. Between steps 2 and 3, it is possible to flow data from passively closing one end to actively closing one end, which is called "half-close". When a Unix process terminates voluntarily (calling exit or returning from the main function) or involuntarily (receiving a signal to terminate the process), all open descriptors are closed, which causes a FIN to be emitted on any TCP connection that is still open. Either side of the client or server can perform an active shutdown. Typically, the customer performs a proactive shutdown, but some protocols, such as HTTP/1.0, are performed by the server.

Tcp in php

Php can use socket function, swoole extension and stream stream function to create socket of tcp protocol, bind network card port, and perform tcp server / client operation. In php, we don't need to know tcp handshake / wave, we just need to know that ip:port can connect / create a tcp server / client.

Using php's socket, we can send strings directly and receive strings. Everything else is language and what the operating system needs to do.

We only need to deal with the integrity of the string, for example, we use php as the tcp server

After the client connection is successful, a string "easyswoole is a very good swoole framework" is sent

While the server only receives 9 bytes at a time, the first acquisition will only receive the incomplete string of "easyswool". You need to continue to get the data.

Process Analysis of http Protocol

The process of a request for http is roughly as follows:

The user enters www.easyswoole.com in the browser

The dns server parses / or native hosts, and the router hosts gets ip by comparison.

If the browser accesses the default port 80, the tcp address accessed is ip:80

Tcp protocol 3-way handshake to establish a connection

Send a http request request header

The server obtains the http request request header, indicating that the access is http access, parsing the http request header, obtaining the request type, request format, and request data (cookie,get,post data)

The server sends response response data and disconnects actively

The browser receives response response data, parses response text types, parses data, and disconnects

In the https protocol, a layer of tls,ssl encryption and decryption protocol is added to the request and response, and the default port is changed from 80 to 443.

Http in phper

Since php is used on web servers most of the time, the protocol that php developers come into contact with most is the http protocol based on tcp/ip protocol.

In fact, among the junior programmers of php, they do not know the http protocol in detail, but you can check the specific request headers of the http protocol and the response headers sent by the server through the browser's f12-> network.

The background of WebSocket protocol

Before there was no WebSocket protocol, in a web page, a chat room could only be polled using ajax to request whether data was generated on the server, and a series of problems would arise in this implementation:

If the polling interval is too short, it will cause the client and the server to continuously carry out the http tcp handshake / wave and the http request header within a period of time, transmit the response header, and consume a lot of server resources. If the number of users is large, it will cause the server to be busy and even downtime.

The client can only get whether the server has returned data by sending http requests each time, and the timeliness of the data cannot be guaranteed.

It is precisely because of this situation that WebSocket appears. It only needs a http handshake to maintain a long connection, so that the server can actively send messages to the client, which greatly reduces the consumption of polling mechanism.

In the process of implementing a websocket connection, you need to issue a websocket connection request through a browser, and then the server sends a response, a process often referred to as a "handshake".

In WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server.

Data can be transmitted directly between the two. In this WebSocket protocol, there are two major benefits for us to implement real-time services:

Header: the Header that communicates with each other is very small-about 2 Bytes

Server Push: the push of the server. The server no longer passively receives the request from the browser before returning data, but actively pushes the data to the browser when new data is available.

Udp (Transport layer)

UDP is the abbreviation of User Datagram Protocol, the Chinese name is user Datagram protocol, and it is a connectionless transport layer protocol in the reference model of OSI (Open System Interconnection). It provides transaction-oriented simple and unreliable information transmission service. IETF RFC 768 is the official specification of UDP. The protocol number of UDP in the IP message is 17.

The full name of UDP protocol is user Datagram protocol. It is a connectionless protocol, which is used to process data packets like TCP protocol in the network. In the OSI model, the fourth layer, the transport layer, is in the upper layer of the IP protocol. UDP does not provide packet grouping, assembly and sorting of packets, that is to say, when a message is sent, it is impossible to know whether it arrives safely and completely. UDP is used to support network applications that need to transfer data between computers. Many client / server mode network applications, including network video conference system, need to use UDP protocol. UDP has been used for many years since it came out. Although its initial brilliance has been overshadowed by some similar protocols, UDP is still a very practical and feasible network transport layer protocol even today.

Like the well-known TCP (Transmission Control Protocol) protocol, the UDP protocol is directly at the top of the IP (Internet Protocol) protocol. According to the OSI (Open Systems Interconnection) reference model, both UDP and TCP are transport layer protocols. The main function of UDP protocol is to compress the network data traffic into data packets. A typical packet is a unit of binary data transmission. The first 8 bytes of each packet are used to contain header information, and the remaining bytes are used to contain specific transmission data.

Udp and tcp

Both udp and tcp belong to the transport layer, and both are at the top of the ip protocol. There are some differences between them:

Udp is a connectionless protocol and does not require a tcp handshake.

The maximum length of each send of udp is 65535, while tcp can send it continuously after shaking hands.

The udp protocol uses the check value in the header to ensure the security of the data. The check value is first calculated by the data sender through a special algorithm, and needs to be recalculated after it is transmitted to the receiver. If a Datagram is tampered with by a third party during transmission or is damaged due to line noise and other reasons, the check calculation values of the sender and receiver will not match, so the UDP protocol can detect whether there is an error. This is different from the TCP protocol, which requires a check value.

Udp message has no reliability guarantee, sequence guarantee and flow control field, so its reliability is poor. However, because of the few control options of udp protocol, it is suitable for applications that do not require high reliability, such as DNS, TFTP, SNMP and so on because of its small delay and high data transmission efficiency.

In the environment of unsatisfactory network quality, the packet loss of UDP protocol will be more serious. And tcp will confirm and verify to ensure that the other party receives it successfully.

Udp can broadcast all hosts in the gateway.

The concept of php multiprocess and multiprocess

As mentioned earlier, multi-process is mainly in the development business logic level, parallel processing of multiple tasks of the development way, what is called the development business logic level?

As we mentioned above, php-fpm is the process manager of fast-cgi. After startup, multiple fast-cgi processes are started, waiting for the task to be processed.

At the php-fpm software level, multiple processes in fast-cgi belong to multi-process processing, but when a user initiates a request

When nginx is handed over to php-fpm to process the request, at this level, each request actually occupies only one php fast-cgi process for processing logic. For the php process running business logic, it is actually a single process.

Similarly, when we run a php file directly, the default is to open only one php process to run php code

Multi-process development scenario

In the traditional web mode, php has always been a single-process business logic, only in php-cli mode, used to deal with asynchronous tasks, as a network server, it is possible to use multi-process processing, so most phper are not familiar with the concept of php multi-process.

Use pcntl to extend process communication

Pipeline communication, divided into famous pipeline, unnamed pipeline, etc., you can search for details.

Message queuing communication, using linux message queuing, through sysvmsg extension, you can see: http://www.php20.cn/article/137

For process signal communication, please see: http://www.php20.cn/article/134

Shared memory communication, mapping a piece of memory that can be accessed by other processes. This shared memory is created by one process, but can be accessed by multiple processes.

Shared memory is the fastest IPC mode, and it is specially designed for other inter-process communication modes to run inefficiently.

It is often used in conjunction with other communication mechanisms, such as signal two, to achieve synchronization and communication between processes.

Socket communication

Third-party communication, using file manipulation, mysql,redis and other methods can also achieve communication.

Cooperative process

A co-program is not a process or thread, but its execution process is more like a subroutine, or a function call with no return value.

A program can contain multiple coroutines, which can be compared with a process containing multiple threads, so let's compare collaborators and threads below.

We know that multiple threads are relatively independent, have their own context, switching is controlled by the system, and the co-program is also relatively independent.

It has its own context, but its switching is controlled by itself, and the switching from the current protocol to other programs is controlled by the current program.

Cooperative process and process

From the code 2 in the execution order of the co-program above, it is easy to find that the co-program is actually a function running in a process, but this function will be switched to the next execution, so to speak:

A co-program is just a string of task codes running in a process, but these task codes can be run across each other. note that the co-program is not multi-task parallel, but belongs to multi-task serial, and each process only executes one task at a time.

Scope of collaborative process

Because the co-program is a series of task codes in the process, its global variables, static variables and other variables are shared, including the global buffer of php.

Therefore, in the development, we need to pay special attention to the global variables and static variables in the co-program. as long as it is modified in a certain co-program, it will affect all the co-programs. When using the ob buffer function to intercept, we have to consider whether it will be contaminated by the output of other co-programs.

Explained by code 2 in the execution order of the co-program, when task1 assigns $_ GET ['name'] to 1, task2 reads $_ GET [' name'] will also be 1. When task 2 assigns $_ GET ['name'] to 2, task3 reads $_ GET [' name'] will also be 2.

Istroke O connection in collaboration process

In the process of cooperation, we should pay special attention to not sharing a single I hand O connection, otherwise it will cause data exception. Explained by the code 2 in the execution order of the co-program, when the task1,task2 functions share the mysql connection and query, because the co-program is cross-run, it may cause task1 to obtain the data queried by task1+task2, or lose part of the data and be acquired by task2.

Due to the cross-running mechanism of mysql,redis, we need to create a connection in each co-program. However, due to the limited number of connections and the consumption of a lot of resources for opening and closing connections, we can use connection pooling scheme to implement shared connections (as long as we ensure that only one co-program is in use for each connection).

At this point, I believe you have a deeper understanding of "what are the knowledge points of swoole?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report