Swoole ( TCP / UDP / Http / Websocket )

TCP - Server/Client

<?php
	
/**
* 创建 TCP Server 对象
*/
// 创建Server对象,监听 127.0.0.1:9501端口
$serv = new Swoole\Server("127.0.0.1", 9501); 

/**
* 绑定参数
*/
$serv->set([
	'worker_num' => 8, // worker进程数 cpu1-4倍
	'max_request' => 10000, // 根据内存定义 https://wiki.swoole.com/#/server/setting
]);

/**
* $fd 客户端连接服务端的唯一标识 ID自增形式 有最大值
* $reactor_id 线程 id
*/
// 监听连接进入事件
$serv->on('Connect', function ($serv, $fd, $reactor_id) {  
	echo "Client: {$reactor_id} - {$fd} - Connect.\n";
});

/**
* $reactor_id 发送的目的地ID
*/
// 监听数据接收事件
$serv->on('Receive', function ($serv, $fd, $reactor_id, $data) {
	$serv->send($fd, "Server: {$reactor_id} - {$fd}".$data);
});

// 监听连接关闭事件
$serv->on('Close', function ($serv, $fd) {
	echo "Client: Close.\n";
});

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

//使用telnet工具测试server开启状态
<?php

// 创建 tcp 客户端服务
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect("127.0.0.1", 9501)) exit("连接失败");

// php cli 常量
fwrite(STDOUT, "请输入消息:");
$msg = trim(fgets(STDIN));

// 发送消息给tcp server服务器
$client->send($msg);

// 接收来自server 的数据
$result = $client->recv();
        
echo $result;

查看端口占用程序命令 lsof -i :9501   /    netstat -anvp tcp  | grep 9501

UDP - Server/Client

     https://wiki.swoole.com/#/start/start_udp_server 


HttpServer

<?php

/**
 * 创建HttpServer
 */
$http = new swoole_http_server("0.0.0.0", 8811);

$http->on('request', function($request, $response) {
	$response->cookie('mingzi', 'neirong', time() + 1800);
	$response->end(json_encode($request->get));
});

$http->start();

有静态资源的HttpServer

<?php

/**
 * 创建HttpServer
 */
$http = new swoole_http_server("0.0.0.0", 8811);

// 需要访问静态资源需要打开配置 并且定义静态资源的文件所在位置 如果http请求有静态资源的名称则会访问静态资源的文件 不会访问on('request')部分
// 目录级的静态资源可以以下方式访问 (目录级/index_next.html/next/index_next.html)
// 访问资源可以是 http://127.0.0.1:8811/index_next.html
// 也可以是 http://127.0.0.1:8811/next/index_next.html
$http->set([
	'enable_static_handler' => true,
	'document_root' => '/Applications/MAMP/htdocs/swoole学习/swoole_demo/data'
]);

$http->on('request', function($request, $response) {
	$response->cookie('mingzi', 'neirong', time() + 1800);
	$response->end(json_encode($request->get));
});

$http->start();

WebSocket

<?php
/**
 * websocket 服务
 */
// 简介
// 	websocket 协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器的双全公工(full-duplex)通信---允许服务器主动发送信息给客户端
// 为什么需要WebSocket
// 	缺陷:Http的通信只能由客户端发起
// WebSocket特点
// 	建立在TCP协议之上
// 	性能开销小通信高效
// 	客户端可以与任意服务器通信
// 	协议标识符ws wss
// 	持久化网络通信协议(长连接)

	
$server = new swoole_websocket_server("0.0.0.0", 8812);

// 可以同时开启http_server 与websocket访问静态资源  也可以单独开启websocket 访问静态资源 区别可以在网络的header中找到 需要访问静态资源需要打开配置 并且定义静态资源的文件所在位置 
// 目录级的静态资源可以以下方式访问
// 访问资源可以是 http://127.0.0.1:8811/index_next.html
// 也可以是 http://127.0.0.1:8811/next/index_next.html
$http->set([
	'enable_static_handler' => true,
	'document_root' => '/Applications/MAMP/htdocs/swoole学习/swoole_demo/data'
]);

// 监听ws连接打开事件
$server->on('open', 'onOpen');
function onOpen($server, $request) {
	echo $request->fd;
};

// 监听ws消息事件
$server->on('message', function ($server, $frame) {
	echo "recive from {$frame->fd} : {$frame->data}, opcode : {$frame->opcode}, fin : {$frame->finish}\n";
	$server->push($frame->fd, '我收到了 回给你一句话');
});

$server->on('close', function ($ser, $fd) {
	echo "client {$fd} closed\n";
});

$server->start();

websocket_html部分

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>第一个swoole-websocket-demo</title>
</head>
<body>
	<h1>测试 websocket</h1>
	<script type="text/javascript">
		var wsUrl = "ws://127.0.0.1:8812";

		var websocket = new WebSocket(wsUrl);

		// 实例对象的onopen
		websocket.onopen = function (evt) {
			websocket.send('你好')
			console.log('连接成功!')
		}

		// 实例化onmessage
		websocket.onmessage = function(evt) {
			console.log('服务端返回的数据' + evt.data)
		}

		// 实例化close事件
		websocket.onclose = function(evt) {
			console.log('close');
		}

		// 错误事件
		websocket.onerror = function(evt, e) {
			console.log('错误信息' + evt.data)
		}

	</script>
</body>
</html>


优化后的websocket

<?php

/**
 * ws优化
 */
class Ws
{

	CONST HOST = "0.0.0.0";
	CONST PORT = 8812;

	public $ws = null;
	public function __construct() 
	{
 		$this->ws = new swoole_websocket_server("0.0.0.0", 8812);

 		$this->ws->on("open", [$this, 'onOpen']);
 		$this->ws->on("message", [$this, 'onMessage']);
 		$this->ws->on("close", [$this, 'onClose']);

 		$this->ws->start();
	}	

	/**
	 * 监听ws连接事件
	 * @Author   Jartin
	 * @Url      string
	 * @DateTime 2020-03-22T19:23:40+0800
	 * @param    [type]                   $ws      [description]
	 * @param    [type]                   $request [description]
	 * @return   [type]                            [description]
	 */
	public function onOpen($ws, $request)
	{		
		var_dump($request->fd);
	}

	/**
	 * 监听ws消息事件
	 * @Author   Jartin
	 * @Url      string
	 * @DateTime 2020-03-22T19:25:25+0800
	 * @param    [type]                   $ws    [description]
	 * @param    [type]                   $frame [description]
	 * @return   [type]                          [description]
	 */
	public function onMessage($ws, $frame)
	{
		echo "服务端监听到客户端的消息:{$frame->data}\n";
		$ws->push($frame->fd, "服务端返回给客户端数据:" . date('Y-m-d H:i:s', time()));
	}

	/**
	 * 
	 * @Author   Jartin
	 * @Url      string
	 * @DateTime 2020-03-22T19:28:44+0800
	 * @param    [type]                   $ws [description]
	 * @param    [type]                   $fd [description]
	 * @return   [type]                       [description]
	 */
	public function onClose($ws, $fd) 
	{
		echo "客户端ID:{$fd}\n";
	}
}
	
$obj = new Ws();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值