# 创建UDP服务器

建议先阅读官方文档的以下章节.

* [创建UDP服务器](https://wiki.swoole.com/wiki/page/477.html)

## 创建UDP服务器

```php
<?php

//创建Server对象，监听 0.0.0.0:9501端口
$serv = new swoole_server("0.0.0.0", 9501,SWOOLE_PROCESS,SWOOLE_SOCK_UDP);

//配置
$serv->set([
    'worker_num' => 2, //设置进程
]);

//接收到udp数据的时候触发
$serv->on('Packet',function ($serv,$data,$clientInfo){
        //var_dump($data,$clientInfo);
        $serv->sendto($clientInfo['address'],$clientInfo['port'],'服务端udp数据包');
});

//启动服务器
$serv->start();
```

UDP服务器与TCP服务器不同，UDP没有连接的概念。启动Server后，客户端无需Connect，直接可以向Server监听的9502端口发送数据包。对应的事件为onPacket。

* `$clientInfo`是客户端的相关信息，是一个数组，有客户端的IP和端口等内容
* 调用`$server->sendto`方法向客户端发送数据

## 创建UDP客户端

```php
$client = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_SYNC);

//不计后果
var_dump($client->sendto('127.0.0.1', 9501,'udp数据'));
//从服务端接收数据
$response = $client->recv();

// 输出接受到的数据
echo $response . PHP_EOL;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/swoole/swoole-ji-chu/wang-luo-tong-xin-yin-qing/chuang-jian-udp-fu-wu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
