How to create a UDP server with swoole (code example)

不言
Release: 2023-04-04 18:46:02
forward
3180 people have browsed it

The content of this article is about the method (code example) of swoole to create a UDP server. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

udp_server.php

<?php
// 创建Server对象,监听 127.0.0.1:9502端口,类型为SWOOLE_SOCK_UDP
$serv = new swoole_server(&#39;127.0.0.1&#39;, 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);

// 监听数据接收事件
$serv->on(&#39;Packet&#39;, function ($serv, $data, $clientInfo) {
    $serv->sendto($clientInfo[&#39;address&#39;], $clientInfo[&#39;port&#39;], &#39;Server &#39; . $data);
    var_dump($clientInfo);
});

// 启动服务器
$serv->start();
Copy after login

The UDP server has no concept of connection. After startup, the client does not need to connect and can directly send data packets to the port monitored by the server. $clientInfo is client-related information

1. Start the service

$ /usr/local/php/bin/php udp_server.php
Copy after login

2. After successful startup, check netstat

$ ps aux | grep php    
oosten   22944  0.0  2.2 314416 23220 pts/4    Sl+  10:49   0:00 /usr/local/php/bin/php udp_server.php
oosten   22945  0.0  0.4 240032  4084 pts/4    S+   10:49   0:00 /usr/local/php/bin/php udp_server.php
oosten   22947  0.0  0.7 244732  7148 pts/4    S+   10:49   0:00 /usr/local/php/bin/php udp_server.php
Copy after login

3.nc connect to the server

$ nc -u 127.0.0.1 9502 ###-u,使用udp传输协议hello
Server hello
Copy after login

4. After the client sends the data packet, the server prints the $clientInfo data

array(4) {
  ["server_socket"]=>
  int(3)
  ["server_port"]=>
  int(9502)
  ["address"]=>
  string(9) "127.0.0.1"
  ["port"]=>
  int(40635)
}
Copy after login

5. End the process

 kill 22944
Copy after login

The above is the detailed content of How to create a UDP server with swoole (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template