In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to build TCP services in Swoole. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
You can quickly create a TCP service through Swoole, and create a new file named tcp_server.php. The code is as follows:
You can start the TCP service by executing the following command on the command line:
Php tcp_server.php
After running the command, you can use the netstat tool to check whether the service started successfully, and if you are already listening on port 9501, you can use the telnet/netcat tool to connect to the server.
Telnet 127.0.0.1 9501
HelloServer: hello
How to use netstat tool: netstat-an | grep 9501
Code logic analysis:
With the above code, you can create a TCP service that listens on port 9501. Its logic is simple: when the client $socket sends a hello string over the network, the server replies with an Server:hello string.
Server is an asynchronous server, so it is written in the same way as listening for events. When the corresponding event occurs, the underlying layer will actively call back the specified function. For example, when the amount of a washed TCP connection is entered, the onConnect event callback will be performed, and the onReceive function will be called back when a connection sends data to the server.
Note:
The server can be connected by thousands of clients at the same time, and $fd is the unique identifier of the client connection
$from_id is the thread ID in the callback function of the Receive event
Call the $srver- > send () method to send data to the client connection, and the parameter is $fd Kodak short identifier
Call the $server- > close () method to forcibly close a client connection
The client may actively disconnect, and the onClose event callback will be triggered
Simple detection of not being able to connect to the server:
Under linux, use the netstat-an | grep port to see if the port has been opened and is in the Listening state
After confirmation in the previous step, check the firewall problem again
Note the IP address used by the server. If it is a 127.0.0.1 loopback address, the client can only use 127.0.0.1 to connect.
If you use Ali CVM or Tencent CVM, you need to set the development port in the security permission group.
The TCP service has been started, so let's use Swoole to build a TCP client to connect to the TCP service. Create a new file named tcp_client.php with the following code:
The above code creates a synchronization client for TCP, which is used to connect to the TCP service enabled by server.php. Send a hello world string to the server, and the server returns an Server:hello world string.
Run the following command from the command line to connect to the TCP service:
Php tcp_client.php
Server:hello world
The client is synchronously blocked, and connect/send/recv waits for the IO to complete before returning. Synchronous blocking operations do not consume CPU resources. When the IO operation is not completed, the current process automatically enters sleep mode. When the IO is complete, the operating system wakes up the current process and continues to execute the code down.
The process is as follows:
TCP needs 3 handshakes, so connect needs at least 3 network transmissions.
When sending a small amount of data, $client- > send can be returned immediately. When a large amount of data is sent, the socket buffer may be full and send operations may block.
The recv operation blocks waiting for the server to return data, and the recv time is equal to the sum of the server processing time and the network transmission time.
The TCP client also has an asynchronous, non-blocking implementation. When using asynchronous mode, connect understands that true is returned. But the connection is not actually established. At this point, you cannot use send to send data immediately after connect. You need to determine whether the connection is successful by isConnected () first. When the connection is successful, the system will automatically call back the onConnect function. Only then can you use the send function to send data to the server.
Through the above code, we have implemented the TCP server and the client. When the server and the client establish a TCP connection, how to keep the connection open? Next we will introduce the heartbeat maintenance scheme of TCP server based on Swoole.
Normally, when the client interrupts the TCP connection, it sends a FIN packet and disconnects the handshake 4 times to notify the server. However, in some abnormal cases, such as a sudden power outage of the client or a network exception, the server may not know that the client has been disconnected. Especially in mobile networks, the TCP connection is very unstable, so a mechanism is needed to ensure the effectiveness of the connection between the server and the client.
This mechanism is built into the Swoole extension itself, and developers only need to configure one parameter to enable it. Swool records a timestamp every time it receives data from the client. When the client does not send data to the server within a certain period of time, the server will automatically cut off the connection.
The configuration method is as follows:
The above setting is to detect a heartbeat every 5 seconds, and if a TCP connection does not send data to the server within 10 seconds, the connection will be cut off.
Through the above cases, we have a certain understanding of the event-driven model of Swoole. We will describe the callback event of Swoole in detail below.
Event execution sequence
All event callbacks occur after $server- > start
The last event when the server shutdown program terminates is onShutdown
After the server starts successfully, onStart / onManagerStart / onWorkerStart will execute concurrently in different processes
OnReceive / onConnect / onClose is triggered in the Worker process
OnWorkerStart / onWorkerStop is called once respectively when the Worker / Task process starts / ends.
OnTask event occurs only in task process onFinish event occurs only in Worker process
The above is how to build TCP services in Swoole. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.