Swoole入门 - UDP 服务

说明:机器还是之前的机器,环境还是还是之前的环境。
官方文档绝对是我们的第一手学习资料,也是最有价值的资料,所以请不要丢掉它。
首先进入之前进入我的目录

[zhengzongqiang@localhost server]# pwd
/opt/work/demo/server

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

创建udp服务端文件

[zhengzongqiang@localhost server]$ sudo vim udp.php

这里程序同样要借鉴一下手册;
是的,一定要学会看手册,学会看手册,学习任何知识都是简单的,很多人说Swoole难,学TP简单,可如果你不懂看手册,再简单也是完蛋;我觉得我说的很有道理,此处应该有掌声。


11160165-fcd7fd613de30c76.png

别人只会告诉你这样写,而不会告诉你他是如何借鉴手册的,而我会。
no bb,show code!

//创建Server对象,监听 127.0.0.1:9502端口,类型为SWOOLE_SOCK_UDP
$serv = new swoole_server("127.0.0.1", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); 

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

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

如何测试呢?看手册,最下:
启动服务

php udp.php

UDP服务器可以使用netcat -u 来连接测试

netcat -u 127.0.0.1 9502
hello
Server: hello

问题解决

你可能会遇到netcat命令不存在,而且yum安装不了的问题
进入你下载软件的目录

[zhengzongqiang@localhost softpkg]$ pwd
/opt/softpkg

1.下载安装包

wget https://sourceforge.net/projects/netcat/files/netcat/0.7.1/netcat-0.7.1.tar.gz

2.解压缩文件

tar -zxvf netcat-0.7.1.tar.gz -C /opt/soft

进入解压目录,可以看到解压后的目录

[zhengzongqiang@localhost soft]$ pwd
/opt/soft
[zhengzongqiang@localhost soft]$ ls
netcat-0.7.1  php
[zhengzongqiang@localhost soft]$ cd netcat-0.7.1

3.编译安装

扫描二维码关注公众号,回复: 6469026 查看本文章
// 1>查看编译配置文件
./configure
// 2>编译安装
make && make install

4.配置环境变量

vim /etc/profile
// 添加环境变量如下
export NETCAT_HOME=/opt/soft/netcat-0.7.1
export PATH=$PATH:$NETCAT_HOME/bin

5.保存退出后,执行以下命令使配置生效

source /etc/profile

4>查看netcat是否已经生效,显示以下信息说明安装成功

[zhengzongqiang@localhost etc]$ nc -V
netcat (The GNU Netcat) 0.7.1
Copyright (C) 2002 - 2003  Giovanni Giacobbi

This program comes with NO WARRANTY, to the extent permitted by law.
You may redistribute copies of this program under the terms of
the GNU General Public License.
For more information about these matters, see the file named COPYING.

Original idea and design by Avian Research <[email protected]>,
Written by Giovanni Giacobbi <[email protected]>.

ps: 遇到问题,第一个找的应该是官网文档!比如我们遇到没有netcat命令不存在的命令,这个如何安装,第一选择当然是官方文档。

猜你喜欢

转载自blog.csdn.net/weixin_33676492/article/details/90895286
今日推荐