Skip to content

Commit

Permalink
ws-server: bug fixed for connection info lost. fix cannot connect to …
Browse files Browse the repository at this point in the history
…root path
  • Loading branch information
inhere committed May 2, 2018
1 parent 53c44c1 commit 55bf3cd
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 134 deletions.
9 changes: 5 additions & 4 deletions src/Event/WsEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
*/
final class WsEvent
{
const ON_HANDSHAKE = 'handshake';
const ON_OPEN = 'open';
const ON_MESSAGE = 'message';
const ON_CLOSE = 'close';
const ON_HANDSHAKE = 'ws.handshake';
const ON_OPEN = 'ws.open';
const ON_MESSAGE = 'ws.message';
const ON_CLOSE = 'ws.close';
const ON_ERROR = 'ws.error';
}
12 changes: 12 additions & 0 deletions src/Exception/ContextLostException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Swoft\WebSocket\Server\Exception;

/**
* Class ContextLostException
* @package Swoft\WebSocket\Server\Exception
*/
class ContextLostException extends \RuntimeException
{

}
2 changes: 0 additions & 2 deletions src/HandlerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,12 @@ public function checkHandshake(Request $request, Response $response): array ;
* @param Server $server
* @param Request $request
* @param int $fd
* @return mixed
*/
public function onOpen(Server $server, Request $request, int $fd);

/**
* @param Server $server
* @param Frame $frame
* @return mixed
*/
public function onMessage(Server $server, Frame $frame);

Expand Down
11 changes: 11 additions & 0 deletions src/Helper/Functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,14 @@
* Date: 2018/3/18
* Time: 下午11:57
*/


if (!function_exists('ws')) {
/**
* @return \Swoft\WebSocket\Server\WebSocketServer
*/
function ws(): \Swoft\WebSocket\Server\WebSocketServer
{
return \Swoft\App::$server;
}
}
65 changes: 43 additions & 22 deletions src/Router/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

namespace Swoft\WebSocket\Server\Router;

use Swoft\App;
use Swoft\Core\ErrorHandler;
use Swoft\Http\Message\Server\Request;
use Swoft\Http\Message\Server\Response;
use Swoft\WebSocket\Server\Event\WsEvent;
use Swoft\WebSocket\Server\Exception\ContextLostException;
use Swoft\WebSocket\Server\HandlerInterface;
use Swoft\WebSocket\Server\Exception\WsMessageException;
use Swoft\WebSocket\Server\Exception\WsRouteException;
use Swoft\WebSocket\Server\WebSocketContext;
use Swoole\WebSocket\Frame;
Expand All @@ -31,15 +33,15 @@ public function handshake(Request $request, Response $response): array
{
try {
$path = $request->getUri()->getPath();
list($className, ) = $this->getHandler($path);
list($className,) = $this->getHandler($path);
} catch (\Throwable $e) {
/* @var ErrorHandler $errorHandler */
// $errorHandler = \bean(ErrorHandler::class);
// $response = $errorHandler->handle($e);
if ($e instanceof WsRouteException) {
return [
HandlerInterface::HANDSHAKE_FAIL,
$response->withStatus(404)
$response->withStatus(404)->withAddedHeader('Failed-Reason', 'Route not found')
];
}

Expand Down Expand Up @@ -70,7 +72,7 @@ public function handshake(Request $request, Response $response): array
public function open(Server $server, Request $request, int $fd)
{
$path = $request->getUri()->getPath();
list($className, ) = $this->getHandler($path);
list($className,) = $this->getHandler($path);

/** @var HandlerInterface $handler */
$handler = \bean($className);
Expand All @@ -86,21 +88,34 @@ public function open(Server $server, Request $request, int $fd)
* @param Frame $frame
* @throws \InvalidArgumentException
* @throws \Swoft\WebSocket\Server\Exception\WsRouteException
* @throws \Swoft\WebSocket\Server\Exception\WsMessageException
* @throws \Swoft\WebSocket\Server\Exception\ContextLostException
*/
public function message(Server $server, Frame $frame)
{
$fd = $frame->fd;

if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new WsMessageException("The connection info has lost of the fd $fd");
}
try {
if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new ContextLostException("The connection info has lost of the fd#$fd, on message");
}

list($className, ) = $this->getHandler($path);
$className = $this->getHandler($path)[0];

/** @var HandlerInterface $handler */
$handler = \bean($className);
$handler->onMessage($server, $frame);
/** @var HandlerInterface $handler */
$handler = \bean($className);
$handler->onMessage($server, $frame);
} catch (\Throwable $e) {
/** @var \Swoft\Event\EventManager $em */
$em = App::getBean('eventManager');

if ($em->hasListenerQueue(WsEvent::ON_ERROR)) {
App::trigger(WsEvent::ON_ERROR, $frame, $e);
} else {
App::error($e->getMessage(), ['fd' => $fd, 'data' => $frame->data]);
// close connection
$server->close($fd);
}
}
}

/**
Expand All @@ -109,21 +124,27 @@ public function message(Server $server, Frame $frame)
* @param int $fd
* @throws \InvalidArgumentException
* @throws \Swoft\WebSocket\Server\Exception\WsRouteException
* @throws \Swoft\WebSocket\Server\Exception\WsMessageException
* @throws \Swoft\WebSocket\Server\Exception\ContextLostException
*/
public function close(Server $server, int $fd)
{
if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new WsMessageException("The connection info has lost of the fd $fd");
}
try {
if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new ContextLostException(
"The connection info has lost of the fd#$fd, on connection closed"
);
}

list($className, ) = $this->getHandler($path);
$className = $this->getHandler($path)[0];

/** @var HandlerInterface $handler */
$handler = \bean($className);
/** @var HandlerInterface $handler */
$handler = \bean($className);

if (\method_exists($handler, 'onClose')) {
$handler->onClose($server, $fd);
if (\method_exists($handler, 'onClose')) {
$handler->onClose($server, $fd);
}
} catch (\Throwable $e) {
App::error($e->getMessage(), ['fd' => $fd]);
}
}

Expand All @@ -141,7 +162,7 @@ protected function getHandler(string $path): array

if ($status !== HandlerMapping::FOUND) {
throw new WsRouteException(sprintf(
'The requested websocket route "%s" path is not exist! ',
'The requested websocket route "%s" path is not exist!',
$path
));
}
Expand Down
4 changes: 2 additions & 2 deletions src/Router/HandlerMapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class HandlerMapping implements HandlerMappingInterface
* ...
* ]
*/
private $routes = [];
protected $routes = [];

/**
* @param string $path
Expand Down Expand Up @@ -59,7 +59,7 @@ public function getHandler(...$params): array
*/
public function match(string $path): array
{
$path = \rtrim($path, '/ ');
$path = $path === '/' ? $path : \rtrim($path, '/ ');

if (!isset($this->routes[$path])) {
return [self::NOT_FOUND, $path];
Expand Down
68 changes: 52 additions & 16 deletions src/WebSocketContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class WebSocketContext
* fd => [
// metadata
* 'meta' => [
* 'id' => fd,
* 'fd' => fd,
* 'path' => request path,
* ...
* ],
Expand All @@ -48,24 +48,35 @@ class WebSocketContext
* ]
* @param Request $request
*/
public static function set(int $fd, array $meta, Request $request)
public static function init(int $fd, array $meta, Request $request)
{
self::$connections[$fd][self::META_KEY] = $meta;
self::$connections[$fd][self::REQUEST_KEY] = $request;
}

/**
* @param int $fd
* @param string $ctxKey
* @param mixed $ctxValue
*/
public static function set(int $fd, string $ctxKey, $ctxValue)
{
self::$connections[$fd][$ctxKey] = $ctxValue;
}

/**
* @param int $fd
* @param string|null $ctxKey
* @return array|null
*/
public static function get(int $fd = null)
public static function get(int $fd = null, string $ctxKey = null)
{
if ($fd === null) {
$fd = self::getFdByCoId();
if ($fd === null && !($fd = self::getFdByCoId())) {
return null;
}

if ($fd === null) {
return null;
}
if ($ctxKey) {
return self::getContext($ctxKey, $fd);
}

return self::$connections[$fd] ?? null;
Expand All @@ -86,12 +97,8 @@ public static function has(int $fd): bool
*/
public static function del(int $fd = null)
{
if ($fd === null) {
$fd = self::getFdByCoId();

if ($fd === null) {
return false;
}
if ($fd === null && !($fd = self::getFdByCoId())) {
return false;
}

if (isset(self::$connections[$fd])) {
Expand All @@ -102,6 +109,34 @@ public static function del(int $fd = null)
return false;
}

/**
* @param string $ctxKey
* @param int|null $fd
* @return mixed|null
*/
public static function getContext(string $ctxKey, int $fd = null)
{
if ($fd === null && !($fd = self::getFdByCoId())) {
return null;
}

return self::$connections[$fd][$ctxKey] ?? null;
}

/**
* @param string $ctxKey
* @param int $fd
* @return bool
*/
public static function hasContext(string $ctxKey, int $fd = null): bool
{
if ($fd === null && !($fd = self::getFdByCoId())) {
return false;
}

return isset(self::$connections[$fd][$ctxKey]);
}

/**
* @return int
*/
Expand Down Expand Up @@ -224,11 +259,12 @@ public static function getFdByCoId()

/**
* delete coId to fd mapping
* @param int|null $cid
* @return bool
*/
public static function delFdToCoId(): bool
public static function delFdToCoId(int $cid = null): bool
{
$cid = self::getCoroutineId();
$cid = $cid > -1 ? $cid : self::getCoroutineId();

if (isset(self::$map[$cid])) {
unset(self::$map[$cid]);
Expand Down
Loading

0 comments on commit 55bf3cd

Please sign in to comment.