Skip to content

Commit

Permalink
предварительные доработки закончены, начато внедрение phpunit тестов
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruslan committed May 31, 2016
1 parent 1755065 commit cad0b2d
Show file tree
Hide file tree
Showing 9 changed files with 174 additions and 57 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
*.iml
out
gen
*.log
*.log
phpunit.phar
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
Event-based sockets for php

## Use sample
Sample for using Esockets in file sample/index.php
Sample for using Esockets in file sample/index.php

### Which PHP version is supported?
Supported PHP5.4 or higher version
21 changes: 21 additions & 0 deletions autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/**
* Created by PhpStorm.
* User: yarullin
* Date: 31.05.2016
* Time: 21:12
*/
spl_autoload_register(function ($class) {
$parts = explode('\\', $class);

# Support for non-namespaced classes.
//$parts[] = str_replace('_', DIRECTORY_SEPARATOR, array_pop($parts));
$parts = [end($parts)];

$path = implode(DIRECTORY_SEPARATOR, $parts);

$file = stream_resolve_include_path(__DIR__ . '/src/' . $path . '.php');
if ($file !== false) {
require $file;
}
});
21 changes: 11 additions & 10 deletions sample/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* Date: 12.12.2015
* Time: 18:10
*/

/*
spl_autoload_register(function ($class) {
$parts = explode('\\', $class);
Expand All @@ -19,8 +19,9 @@
if ($file !== false) {
require $file;
}
});
});*/

require '../autoload.php';

define('INTERVAL', 1000); // 1ms

Expand Down Expand Up @@ -78,16 +79,16 @@ function error_type($type)
});

$server = new \Esockets\Server();
if (!$server->open()) {
if (!$server->connect()) {
echo ' Не удалось запустить сервер! <br>' . PHP_EOL;
exit;
}
$server->onAccept(function ($peer) {
$server->onConnectPeer(function ($peer) {
/**
* @var $peer \Esockets\Peer
*/
error_log(' Принял ' . $peer->getAddress() . ' !');
$peer->onReceive(function ($msg) use ($peer) {
$peer->onRead(function ($msg) use ($peer) {
/**
* @var $this \Esockets\Peer
*/
Expand All @@ -106,14 +107,14 @@ function error_type($type)
$client->onDisconnect(function () {
error_log('Меня отсоединили или я сам отсоединился!');
});
$client->onReceive(function ($msg) {
$client->onRead(function ($msg) {
error_log('Получил что то: ' . $msg . ' !');
});

$work = new \Esockets\WorkManager();
$work->addWork('serverAccept', [$server, 'doAccept'], [], ['always' => true, 'interval' => 5000]);
$work->addWork('serverReceive', [$server, 'doReceive'], [], ['always' => true, 'interval' => 1000]);
$work->addWork('clientReceive', [$client, 'doReceive'], [], ['always' => true, 'interval' => 1000]);
$work->addWork('serverAccept', [$server, 'listen'], [], ['always' => true, 'interval' => 5000]);
$work->addWork('serverReceive', [$server, 'read'], [], ['always' => true, 'interval' => 1000]);
$work->addWork('clientReceive', [$client, 'read'], [], ['always' => true, 'interval' => 1000]);

$work->execWork();

Expand All @@ -130,7 +131,7 @@ function error_type($type)
}
$work->deleteWork('serverReceive');

$server->close();
$server->disconnect();

for ($i = 0; $i < 2; $i++) {
$work->execWork();
Expand Down
7 changes: 6 additions & 1 deletion src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ class Client extends Net

public function connect()
{
return $this->connected ?: $this->_connect();
return $this->is_connected() ?: $this->_connect();
}

public function is_connected()
{
return $this->connected;
}

public function disconnect()
Expand Down
13 changes: 13 additions & 0 deletions src/Peer.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ public function __construct(&$connection, $dsc)
return false;
}

public function connect()
{
// метод-заглушка
// TODO: Implement connect() method.
}

public function is_connected()
{
return $this->connected;
// TODO: Implement is_connected() method.
}


public function disconnect()
{
parent::disconnect();
Expand Down
96 changes: 53 additions & 43 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ class Server extends Net implements ServerInterface
*/
private $_open_try = false;

public function open()
public function connect()
{
if ($this->opened) return true;
if ($this->is_connected()) return true;

if ($this->connection = socket_create($this->socket_domain, SOCK_STREAM, $this->socket_domain > 1 ? getprotobyname('tcp') : 0)) {
socket_set_option($this->connection, SOL_SOCKET, SO_REUSEADDR, true);
Expand Down Expand Up @@ -95,6 +95,17 @@ public function open()
return false;
}

public function is_connected()
{
return $this->opened;
}

public function disconnect()
{
$this->disconnectAll();
parent::disconnect(); // TODO: Change the autogenerated stub
}

/**
* close server
*/
Expand All @@ -105,7 +116,7 @@ public function disconnectAll()
/**
* @var $peer \Esockets\Peer
*/
$peer->doDisconnect();
$peer->disconnect();
unset($this->connections[$index], $peer);
}

Expand All @@ -121,14 +132,22 @@ public function disconnectAll()
// /@TODO recheck this code
}

public function ping()
public function listen()
{
error_log('Пингуем пиров');
foreach ($this->connections as $peer) {
if ($connection = socket_accept($this->connection)) {
return $this->_onConnectPeer($connection);
}
return false;
}

public function read()
{
foreach ($this->connections as $dsc => $peer) {
/**
* @var $peer \Esockets\Peer
* @var $peer Peer
*/
$peer->ping();
error_log('Читаю пира ' . $peer->getDsc() . ' on adddress ' . $dsc);
$peer->read();
}
}

Expand All @@ -144,11 +163,15 @@ public function send($data)
return $ok;
}

public function doDisconnect($client)
public function ping()
{
/**
* TODO
*/
error_log('Пингуем пиров');
foreach ($this->connections as $peer) {
/**
* @var $peer \Esockets\Peer
*/
$peer->ping();
}
}

/**
Expand All @@ -166,26 +189,6 @@ protected function _onDisconnect()
}
}

public function onDisconnectPeer(callable $callback)
{
$this->event_disconnect_peer = $callback;
}

public function _onDisconnectPeer(Peer $peer)
{
if (is_callable($this->event_disconnect_peer)) {
call_user_func_array($this->event_disconnect_peer, [$peer]);
}
}

public function listen()
{
if ($connection = socket_accept($this->connection)) {
return $this->_onConnectPeer($connection);
}
return false;
}

/**
* @param callable $callback ($peer)
* Give callback function($client)
Expand All @@ -195,17 +198,6 @@ public function onConnectPeer(callable $callback)
$this->event_accept = $callback;
}

public function read()
{
foreach ($this->connections as $dsc => $peer) {
/**
* @var $peer Peer
*/
error_log('Читаю пира ' . $peer->getDsc() . ' on adddress ' . $dsc);
$peer->read();
}
}

protected function _onConnectPeer(&$connection)
{
while (isset($this->connections[$this->connections_dsc])) {
Expand All @@ -229,4 +221,22 @@ protected function _onConnectPeer(&$connection)
}
}

public function onDisconnectPeer(callable $callback)
{
$this->event_disconnect_peer = $callback;
}

public function _onDisconnectPeer(Peer $peer)
{
if (is_callable($this->event_disconnect_peer)) {
call_user_func_array($this->event_disconnect_peer, [$peer]);
}
}

public function onDisconnectAll(callable $callback)
{
// TODO: Implement onDisconnectAll() method.
}


}
20 changes: 19 additions & 1 deletion src/WorkManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ public function execWork();

}

/**
* Class WorkManager
* @package Esockets
*
* Вспомогательный класс для работы как с серверной, так и с клиентской частью сокетов
*/
class WorkManager implements WorkManagerInterface
{
private $_list;
Expand All @@ -45,6 +51,8 @@ public function addWork($key, callable $callback, array $params = [], array $opt
if (!isset($this->_list[$key])) {
$options = [
'always' => false,
'count' => 0, // default unlimited count of execution
'iterations' => 0,
'interval' => 1000,
'executed' => 0,
'result' => true, // result need to complete work
Expand All @@ -63,14 +71,24 @@ public function deleteWork($key)
return true;
}

/**
* Функция запускает выполнение всех заданий.
* Все задания выполняются с заданным минимальным интервалом. Саму функцию можно вызывать с любым интервалом.
* Задачи имеют параметр always, если он установлен в true, то задача является многоразовой,
* и будет выполняться до тех пор, пока результат не будет соответствует установленному ожиданию,
* после чего она автоматически удаляется из списка
* Задачу можно удалять вручную с помощью метода deleteWork()
*/
public function execWork()
{
$mt = microtime(true) * 1000;
foreach ($this->_list as $key => &$item) {
$mt = microtime(true) * 1000;
if ($item['options']['executed'] + $item['options']['interval'] <= $mt) {
$item['options']['executed'] = microtime(true);
error_log('EXEC WORK ' . $key);
$result = call_user_func_array($item['callback'], $item['params']);
// если задача не многоразовая
// и если результат удовлетворяет ожиданиям
if (!$item['options']['always'] && $result == $item['options']['result']) {
$this->deleteWork($key); // if work completed, then may be deleted
}
Expand Down
45 changes: 45 additions & 0 deletions tests/TestEsocketsLinear.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
/**
* Created by PhpStorm.
* User: yarullin
* Date: 31.05.2016
* Time: 21:26
*/

namespace Esockets;


class TestEsockets extends \PHPUnit_Framework_TestCase
{
/**
* @var $server \Esockets\Server
* @var $client \Esockets\Client
*/
private $server, $client;

public function testServerOpen()
{
$this->server = new \Esockets\Server();
$this->assertTrue($this->server->connect(), 'Сервер не создаётся');
}

public function testClientConnect()
{
$this->client = new \Esockets\Client();
$this->assertTrue($this->client->connect(), 'Клиент не может соединиться');
}

public function testServerAcceptClient()
{
$this->server->onConnectPeer(function (\Esockets\Peer $peer) {

});

$this->server->listen();
}

public function testClientSendData()
{
$this->assertTrue($this->client->send('Hello world'), 'Клиент не может отправить данные');
}
}

0 comments on commit cad0b2d

Please sign in to comment.