当前位置:网站首页>Spoole TCP server
Spoole TCP server
2022-07-22 14:34:00 【Life goes on and battles go on】
learning Swoole4 file
tcp
// establish Server object , monitor 127.0.0.1:9501 port
$server = new Swoole\Server('127.0.0.1', 9501);
// Listen for connection entry events
$server->on('Connect', function ($server, $fd) {
echo "Client: Connect.\n";
});
// Listen for data receiving events
$server->on('Receive', function ($server, $fd, $from_id, $data) {
$server->send($fd, "Server: " . $data);
});
// Listen for connection close events
$server->on('Close', function ($server, $fd) {
echo "Client: Close.\n";
});
// Start the server
$server->start();
Create a TCP The server , Monitor local 9501 port . Its logic is simple , When the client Socket Send a message over the network hello When the string , The server will reply one Server: hello character string .
Server It's an Asynchronous Server , So the program is written by listening to events . When the corresponding event occurs, the underlying layer will actively call back the specified function . When there is a new TCP When the connection enters, it executes onConnect Event callback , When a connection sends data to the server, it calls back onReceive function .
The server can be connected by thousands of clients at the same time ,$fd Is the unique identifier of the client connection
call $server->send() Method to send data to the client connection , The parameter is $fd Client identifier
call $server->close() Method to force a client connection to close
The client may take the initiative to disconnect , It's going to trigger onClose Event callback
The general function of the code is :
1) When the server finds that the client is connected , Will output text “Client:Connect”
2) Once the message from the client is received , Will send... To the client “Server: The original message ”
3) When the connection is disconnected , Output text “Client:Close”
Detailed explanation of correlation function
1) Constructors
Swoole\Server(string $host = '0.0.0.0', int $port = 0, int $mode = SWOOLE_PROCESS, int $sockType = SWOOLE_SOCK_TCP): \Swoole\Server
$host: Monitoring IP Address , Can support IPV4 It can also support IPV6,0.0.0.0 by IPV4 All the addresses of ,::( amount to 0:0:0:0:0:0:0:0) by IPV6 All the addresses of .
$port: Listening port , If the port is less than 1024 You need to root jurisdiction .
$mode:SWOOLE_PROCESS( Default , Multi process mode ),SWOOLE_BASE( Basic mode ).
$socketType:SWOOLE_SOCK_TCP( Default ,IPV4 TCP)、SWOOLE_SOCK_TCP6、SWOOLE_SOCK_UDP、SWOOLE_SOCK_UDP6
2) function on: Call event
Swoole\Server->on(string $event, mixed $callback): void
$event: Event name , Case insensitive
$callback: Callback function , For the parameter format of the callback function of each event, see the event description . The callback function can be a string of function name , Class static methods , Object method array , Anonymous functions .
3) function start: Start the server , Listen to all specified ports
Swoole\Server->start(): bool
This function has no parameters , But the following things must be understood :
· After successful startup, it will create worker_num+2 A process .Master process +Manager process +worker_num individual Worker process .
· Startup failure will immediately return false
· After successful startup, it will enter the event cycle , Waiting for client connection request .start The code after the method will not execute
· After the server is shut down ,start The function returns true, And continue down
· Set up task_worker_num The generic value will increase by a corresponding amount Task process
· Method list start The previous method can only be used in start Use before calling , stay start The latter method can only be used in onWorkerStart、onReceive And other event callback functions
4) function send: Send data to client
Swoole\Server->send(int $fd, string $data, int $serverSocket = -1): bool
$fd: Client file descriptor , Each client is assigned a descriptor , It can be understood as the client's ID.
$data: Data sent ,TCP The maximum agreement shall not exceed 2M, Modifiable buffer_output_size Change the maximum packet length allowed to be sent .
$serverSocket: towards UnixSocket DGRAM This parameter is required when sending data to the opposite end ,TCP The client does not need to fill .
5) function getClientInfo: Get connection information
Swoole\Server->getClientInfo(int $fd, int $extraData, bool $ignoreError = false): bool|array
$fd: Client file descriptor , Each client is assigned a descriptor , It can be understood as the client's ID.
$extraData: Extended information , Reserved parameters , There is no effect at present .
$ignoreError: Whether to ignore errors , If set to true, Even if the connection is closed, the connection information will be returned .
Be careful : When using dispatch_mode = 1( Round robin mode ) or 3( Preemption mode ) When the configuration , Consider this packet distribution strategy for stateless Services , When the connection is disconnected, the relevant information will be deleted directly from the memory , therefore Server->getClientInfo Is unable to obtain relevant connection information .
边栏推荐
- 【大型电商项目开发】线程池-异步(CompletableFuture)-48
- Full link voltage test: the dispute between shadow database and shadow table
- 2. ZABBIX concept
- 英国天气过热导致谷歌云、Oracle云服务中断
- With an annual salary of 30W, the growth path of software testers, at which stage are you?
- ByteDance test post, the front has passed, and the last HR sinkhole Tell me that
- 迟迟不发业绩预告,京东方此时无声胜有声?
- 解决v-for中el-popover显示等问题
- 蓝桥杯STEMA科技素养 视频等相关资料收集
- Adaptive length input box
猜你喜欢
State owned enterprises work overtime in 996, but job hopping offers are outsourcing. What should we do?
SOC first project
基于STM32无人超市消费系统设计
Développement d'ardunio - processus de fonctionnement des pompes
Ardunio development - pump operation process
With an annual salary of 30W, the growth path of software testers, at which stage are you?
STM32状态机编程实例——全自动洗衣机(上)
Time complexity and complexity
Three barriers in the workplace: annual salary of 300000, 500000 and 1million
MySql集群之主从复制(一)
随机推荐
半月谈 总结中前行
【每日一题】814. 二叉树剪枝
OA project introduction & Conference release
找100以内的素数,求约数,求两个数的最大公约数
helm --set的使用示例及基本使用命令整理
Summer precipitation Web Learning - SQL injection (Boolean blind injection & time blind injection)
Interlaced color change of table
Parker hydraulic oil pump pvp3336r2m
Swoole-TCP服务器
BOM operation - jog animation
08. Use of octave language - control statements, drawing lines and other commands
5. ZABBIX create a custom key
rexroth力士乐柱塞泵A15VSO
Web自动化-——selenium
day3·文件与目录
Interview problems
Move forward in the summary of half a month's talk
cordove 友盟插件 ++推送和统计功能
dom——事件代理
One of MySQL clusters, master-slave architecture (3)