Basic knowledge of PHP socket network programming (1): Opening



  • Although we seldom use network programming in ordinary web programming, we have been using it all the time. For example, the communication between nginx and PHP FPM is network communication. We will also find that some of their configuration parameters are actually the parameters of some functions in network programming.
  • When we say communication, we take it for granted that it is the communication between two machines, but in fact, the same machine can also communicate and interact through loopback, just like nginx and PHP FPM can be deployed on the same machine, or load balancing can be deployed on multiple machines.
  • PHP itself provides the function of network communication, but most of the related documents have not been translated into Chinese, and the document description and examples are less and abstract, which requires a certain foundation to understand, leading to fewer people to use
  • If you study this aspect, you can’t just look at the documents. You need to query a lot of related information to understand. The query information can not be limited to PHP. Other languages also have network communication, and the principles are common.
  • Here is a brief summary of my knowledge.

Related requirements

Only when we solve practical problems can we really understand the usage and meaning of each method. Let’s assume that if we want to realize the chat between customer service and customers on the web, what problems will we encounter or how to solve them:

  • Although the two chat, but in fact the two are not directly chat, but through the intermediate server transfer, that isCustomer service serverEstablish communicationsCustomer serverThe establishment of communication, similar to sending letters, needs to be forwarded through the post office.
  • This requires the server to access at least two clients (clients and customers) at the same time, but how can the server handle two clients at the same time? At present, what we can think of is to use multi process or multi thread to solve the problem. When a customer accesses and starts a process to process the communication with the customer, the main process will continue to detect whether the customer service has access. If the customer service also accesses, the process processing will also be started.
  • And then aloneCustomer service serverFor this communication, will there be a conflict between reading and writing? Customer service needs to receive messages, but we don’t know when the server (customer) will send messages. It’s natural to use the while loop to detect messages sent by the server all the time, and then it will be stuck. How can I send messages, At present, the solution we can think of is to open a new process or thread to solve the problem of read-write conflict.
  • Our communication usually needs to send a heartbeat packet every other period of time, otherwise if we don’t communicate for a long time, the system will close the connection. There is a problem again. Our program can’t handle reading and writing. How to send heartbeat? The best way we can think of is to open a new process or thread to send heartbeat packets separately.
  • It’s a headache just to think about the problems mentioned above. There are few official documents about processes and threads, let alone the communication between processes and threads. But this is really a solution.
  • Can’t a single process handle it? No, we can use the IO multiplexing method similar to select provided by the system. This method can monitor access, read, write and other events through the system kernel. When an event occurs, you will be notified and then processed. In this way, the above operations can be completed in a process, but the total amount received by a process is limited, So when we want to improve concurrency, we will still use multi process to deal with it, but the logic at this time will be much simpler than that mentioned above. As for the heartbeat packet problem, we can solve it by timer signal, and there is no need to open a new process or thread.
  • Here’s another thing I was very confused about at the beginning of my study. When learning various examples, the messages sent or received are all dead. But our actual requirement is that the user should fill in them. How can I insert them? This is equivalent to inertial thinking. As soon as users fill in, they immediately think of post transmission, and then there is some confusion and conflict. But in fact, for the web chat scenario, the transmission between them is websocket, which is called directly in the customer click to send eventws.sendSend a message in a similar way, and the server receives the message to trigger a read message event, and then forward it to the customer service in the event. For the scenario similar to app push message, the data filled in the background really needs to be sent to the web server by post. Then the web server receives the post data and sends it to the socket server by calling the send similar method. After receiving the message, the socket server broadcasts the message to each socket client. The PHP script is closed after execution, So the web server to the socket server will also be closed, but there is no impact. Just connect again every time. We just need to ensure that the socket server and the client maintain a long connection. The web server only needs to connect to the socket server when the background wants to send push information.
  • Therefore, to realize the above functions, we need to learn the following knowledge points:
    • Socket Foundation
    • Stream Foundation
    • Multiprocess
    • signal
    • IO model

Related PHP functions

  • Socket function, the most basic call, usage and pure C is very similar
  • Stream function, PHP do socket call further encapsulation, more convenient than the above call
  • Pcntl functionSocket programming is generally inseparable from multi process and signal functions
  • POSIX function, process information, user and group management, signaling, etc
  • Libevent function, event driven Library

Relevant information


Originally, there was a project related to Java network communication. At that time, it was not done with PHP, and finally it was done with their Java related SDK, so I always wanted to supplement this knowledge, but I never looked at it. The reason for this is as follows:

  • If you look at the basic knowledge of python, you can see the fields of pack, coroutine and select
  • PHP also has corresponding pack, yield functions, etc., which means to see the differences (in fact, compared with other languages, it can deepen understanding)
  • PHP’s yied is related, and it’s not further encapsulated, while spool claims to handle the collaborative aspect very well
  • Swoole is written in C, but its C foundation is not good, so I want to see a similar workerman written in pure PHP first
  • Workerman is very concise and well written. There are some functions that you can’t understand, so it’s corresponding to checking the related functions


be careful

  • The previous articles have been written for a long time and have been kept in the draft. I plan to write them all before I send them out. However, since I have transferred to Java development, I haven’t finished the subsequent chapters. At present, I have no plan to write them again. Maybe I will wait until I finish learning JavaNettyI will summarize it later. After a long time, I turn to these articles in the draft. I’d better send them out for reference