Skip to content

Commit

Permalink
fixed bug
Browse files Browse the repository at this point in the history
  • Loading branch information
jxy918 committed Aug 23, 2019
1 parent 0d0657c commit d5be768
Show file tree
Hide file tree
Showing 10 changed files with 501 additions and 79 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ composer install
* 2,目录说明(swoft目录不具体说明):

```
./app/Http/Controller/GameController.php 游戏http控制器逻辑
./app/WebSocket/Game 是这个整体游戏服务器逻辑
./app/WebSocket/Game/Conf 逻辑配置目录, 比如:命令字, 子名字, 路由转发
./app/WebSocket/Game/Core 游戏路由转发,算法,解包核心类
Expand Down
124 changes: 54 additions & 70 deletions app/Http/Controller/GameController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,19 @@

namespace App\Http\Controller;

use ReflectionException;
use Swoft;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Carbon\Carbon;
use Throwable;
use Swoole\Coroutine\Http\Client;

use App\WebSocket\Game\Core\Packet;
use App\WebSocket\Game\Conf\MainCmd;
use App\WebSocket\Game\Conf\SubCmd;
use function server;
use const WEBSOCKET_OPCODE_BINARY;

/**
* Class GameController
Expand All @@ -35,16 +36,26 @@ class GameController{
public $userinfo = array();

/**
* consul 发现服务url
* consul 发现服务ip
*/
const DISCOVERY_PATH = 'http://127.0.0.1:8500/v1/health/service/%s?passing=1&dc=dc1&near';
const DISCOVERY_IP = '192.168.7.197';

/**
* consul 发现服务port
*/
const DISCOVERY_PORT = 8500;

/**
* consul 发现服务uri
*/
const DISCOVERY_URI = '/v1/health/service/%s?passing=1&dc=dc1&near';

/**
* game input
* @RequestMapping(route="/game")
* @param Request $request
* @param Response $response
* @return array|Response
* @return Response
*/
public function index(Request $request, Response $response)
{
Expand All @@ -71,7 +82,7 @@ public function login(Request $request, Response $response)
if(!empty($account)) {
//注册登录
$uinfo = array('account'=>$account);
$response = $this->addCookie($request, $response, 'USER_INFO', json_encode($uinfo), 60);
$response = $response->withCookie('USER_INFO', json_encode($uinfo));
return $response->redirect('/test');
} else {
$tips = '温馨提示:用户账号不能为空!';
Expand Down Expand Up @@ -121,62 +132,12 @@ public function broadcast(Request $request)
}
$data = Packet::packFormat('OK', 0, $msg);
$data = Packet::packEncode($data, MainCmd::CMD_SYS, SubCmd::BROADCAST_MSG_RESP);
$serv = App::$server->getServer();
$conn_client = $this->pushToAll($serv, $data);
return $conn_client;
$cnt = server()->sendToAll($data, 0, 50, WEBSOCKET_OPCODE_BINARY);
return ['status'=>0, 'msg'=>'给'.$cnt.'广播了消息'];
}

/**
* set a cookie
* @param Request $request
* @param Response $response
* @param string $key
* @param string $value
* @param int $expire(m)
*/
protected function addCookie(Request $request, Response $response, $key = '', $value = '', $expire = 0)
{
// $uri = $request->getUri();
// $path = '/';
// $domain = $uri->getHost();
// $secure = strtolower($uri->getScheme()) === 'https';
// $httpOnly = false;
// $expire = Carbon::now()->addMinutes($expire);
// $cookie = new Cookie($key, $value, $expire, $path, $domain, $secure, $httpOnly);
$response = $response->withCookie($key, $value);
return $response;
}

/**
* 当connetions属性无效时可以使用此方法,服务器广播消息, 此方法是给所有的连接客户端, 广播消息,通过方法getClientList广播
* @param $serv
* @param $data
*/
protected function pushToAll($serv, $data)
{
$client = array();
$start_fd = 0;
while(true) {
$conn_list = $serv->getClientList($start_fd, 10);
if ($conn_list===false or count($conn_list) === 0) {
Log::show('BroadCast finish');
break;
}
$start_fd = end($conn_list);
foreach($conn_list as $fd) {
//获取客户端信息
$client_info = $serv->getClientInfo($fd);
$client[$fd] = $client_info;
if(isset($client_info['websocket_status']) && $client_info['websocket_status'] == 3) {
$serv->push($fd, $data, WEBSOCKET_OPCODE_BINARY);
}
}
}
return $client;
}

/**
* 广播全服
* 广播全服, 分布式广播, 需要安装consul注册发现服务器
* @RequestMapping(route="/broadcast_to_all")
* @return array
*/
Expand All @@ -189,9 +150,10 @@ public function broadcastToAll(Request $request)
$result = [];
//采用http循环发送消息
foreach($serviceList as $v) {
$notify_url = "http://{$v}/broadcast?msg={$msg}";
$httpClient = new Client();
$result[$v] = $httpClient->get($notify_url)->getResult();
$cli = new Client($v['ip'], $v['port']);
$cli->get("broadcast?msg={$msg}");
$result = $cli->body;
$cli->close();
}
return $result;
}
Expand All @@ -204,9 +166,10 @@ public function broadcastToAll(Request $request)
*/
public function getServiceList($serviceName = 'gateway')
{
$httpClient = new Client();
$url = sprintf(self::DISCOVERY_PATH, $serviceName);
$result = $httpClient->get($url)->getResult();
$cli = new Client(self::DISCOVERY_IP, self::DISCOVERY_PORT);
$cli->get(sprintf(self::DISCOVERY_URI, $serviceName));
$result = $cli->body;
$cli->close();
$services = json_decode($result, true);

// 数据格式化
Expand All @@ -223,10 +186,31 @@ public function getServiceList($serviceName = 'gateway')
}
$address = $serviceInfo['Address'];
$port = $serviceInfo['Port'];

$uri = implode(":", [$address, $port]);
$uri = ['ip'=>$address, 'port'=>$port];
$nodes[] = $uri;
}
return $nodes;
}

/**
* 录像页面
* @RequestMapping(route="/camera")
* @return Response
* @throws Throwable
*/
public function camera()
{
return view('vedio/camera');
}

/**
* 直播页面
* @RequestMapping(route="/show")
* @return Response
* @throws Throwable
*/
public function show()
{
return view('vedio/show');
}
}
2 changes: 1 addition & 1 deletion app/Listener/Test/WorkerStartListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class WorkerStartListener implements EventHandlerInterface
public function handle(EventInterface $event): void
{
$context = context();

CLog::info('Worker Start context=' . get_class($context));
}
}
56 changes: 56 additions & 0 deletions app/TcpServerListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php declare(strict_types=1);

namespace App\Listener;

namespace App\Listener;


use App\Http\Controller\ValidatorController;
use ReflectionException;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Co;
use Swoft\Consul\Agent;
use Swoft\Consul\Exception\ClientException;
use Swoft\Consul\Exception\ServerException;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Server\SwooleEvent;
use Swoole\Coroutine;

/**
* Class TcpServerListener
*
* @since 2.0
*
* @Listener(SwooleEvent::RECEIVE)
*/
class TcpServerListener implements EventHandlerInterface
{
/**
* @Inject()
*
* @var Agent
*/
private $agent;

/**
* @param EventInterface $event
*
* @throws ReflectionException
* @throws ContainerException
* @throws ClientException
* @throws ServerException
*/
public function handle(EventInterface $event): void
{
/* @var HttpServer $httpServer */
$httpServer = $event->getTarget();

var_dump('----------------------------------------');

// $this->agent->deregisterService('swoft');
}
}
1 change: 0 additions & 1 deletion app/WebSocket/GameModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ public function checkHandshake(Request $request, Response $response): array
* @param Request $request
* @param int $fd
*/

public function onOpen(Request $request, int $fd): void
{
$cookie = $request->getCookieParams();
Expand Down
89 changes: 89 additions & 0 deletions app/WebSocket/VedioModule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php
/**
* This file is part of Swoft.
*
* @link https://swoft.org
* @document https://doc.swoft.org
* @contact group@swoft.org
* @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
*/

namespace App\WebSocket;

use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\WebSocket\Server\Annotation\Mapping\OnClose;
use Swoft\WebSocket\Server\Annotation\Mapping\OnHandshake;
use Swoft\WebSocket\Server\Annotation\Mapping\OnOpen;
use Swoft\WebSocket\Server\Annotation\Mapping\OnMessage;
use Swoft\WebSocket\Server\Annotation\Mapping\WsModule;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use function server;
use const WEBSOCKET_OPCODE_BINARY;


/**
* Class VedioModule
*
* @WsModule(
* "/vedio"
* )
*/
class VedioModule
{

/**
* 在这里你可以验证握手的请求信息
* @OnHandshake()
* @param Request $request
* @param Response $response
* @return array [bool, $response]
*/
public function checkHandshake(Request $request, Response $response): array
{
return [true, $response];
}

/**
* @OnOpen()
* @param Request $request
* @param int $fd
*/
public function onOpen(Request $request, int $fd): void
{
echo "vedio connnected #{$fd}...";

}

/**
* @OnMessage()
* @param Server $server
* @param Frame $frame
*/
public function onMessage(Server $server, Frame $frame)
{
//广播消息
echo "vedio message #{$frame->fd}...data:".$frame->data."\n";
if(!is_numeric($frame->data)) {
//如果是录像数据, 发送二进制数据
$ret = server()->sendToAll($frame->data, 0, 50);
var_dump($ret);
}
}


/**
* On connection closed
* - you can do something. eg. record log
*
* @OnClose()
* @param Server $server
* @param int $fd
*/
public function onClose(Server $server, int $fd): void
{
//清除登陆信息变量
echo "vedio close #{$fd}...";
}
}
Loading

0 comments on commit d5be768

Please sign in to comment.