用swoole实现一个简单的服务器消息推送

原理图:


server.php

<?php
//消息提送服务器
$server=new swoole_websocket_server('0.0.0.0',9502);
$server->on('message',function($s,$frame){
	//var_dump($frame);
	//广播
	foreach($s->connection_list() as $v){
		$s->push($v,$frame->data);
	}
});
$server->start();
?>

http.php

<?php

$http=new swoole_http_server('0.0.0.0',8502);

//2.事件驱动
$http->on('request',function($request,$response){
	//echo '有请求';
	//var_dump($request->post);
	//消息转发,发送websocket 请求
	$client=new swoole_http_client('118.240.109.52',8502);
	
	//服务端如果处理成功会推送消息到客户端
	$client->('message',function($client,$frame){
		var_dump($frame);
	});
	
	$client->upgrade('/',function($client){
		$client->push('hello wrold');//推送消息
	});
	//同步阻塞,异步非阻塞
	
});

//3.启动服务
$http->start();

?>

push.html

push.html

<script src="js/jquery.min.js"></script>
<script>
var content=prompt('请输入要发送的内容','');
//ajax异步
$.post("http://voter.com:8502",{content:content},function(data){
	alert('推送成功');
})
</script>


猜你喜欢

转载自blog.csdn.net/taotaobaobei/article/details/80371489
今日推荐