Example #1
0
 public static function getInstance()
 {
     if (!self::$instance) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #2
0
 function __construct($address, $port)
 {
     global $infotv;
     $this->listened = array();
     $this->modules = array();
     $this->modules["slides"] = new infotv_slides_module($this);
     add_option($infotv->prefix . "websocket_status", 2);
     parent::__construct($address, $port);
 }
 function __construct()
 {
     global $wgExtensionFunctions;
     // Extension setup hook
     $wgExtensionFunctions[] = 'WebSocket::setup';
     // Give this client an ID or use that supplied in request
     self::$clientID = array_key_exists('clientID', $_REQUEST) ? $_REQUEST['clientID'] : uniqid('WS');
     // Is this an SSL connection?
     self::$ssl = array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'];
 }
Example #4
0
 public function __construct($url)
 {
     $this->url = str_replace("ws://", "http://", $url);
     preg_match("!^http://(.*):(\\d+)/(.*)\$!", $this->url, $match);
     $this->ip = $match[1];
     $this->port = $match[2] + 1;
     $this->scope = $match[3];
     \eTools\Utils\Logger::log("Setting WebSocket fix to " . $this->ip . ":" . $this->port);
     if (self::$sock == null) {
         self::$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     }
 }
Example #5
0
 function test_DoubleEchoResourceHandlerResponse()
 {
     $input = str_repeat("a", 1024);
     $input2 = str_repeat("b", 1024);
     $msg = WebSocketMessage::create($input);
     $client = new WebSocket("ws://127.0.0.1:12345/echo/");
     $client->setTimeOut(1000);
     $client->open();
     $client->sendMessage($msg);
     $client->sendMessage(WebSocketMessage::create($input2));
     $msg = $client->readMessage();
     $msg2 = $client->readMessage();
     $client->close();
     $this->assertEquals($input, $msg->getData());
     $this->assertEquals($input2, $msg2->getData());
 }
Example #6
0
 public function disconnect($socket)
 {
     $id = $this->players->delPlayer($socket);
     // a player disconnected so send to all
     $this->sendToAll($socket, Commands::PLAYER_DISCONNECT . $this->commandee->setPlayer($id));
     $map_id = $this->maps->getMapByPlayerId($id);
     if ($map_id !== NULL) {
         $map_id = $map_id->getId();
         // the map's other player state goes to free and send him to a game over message
         $other_player = $this->maps->getMap($map_id)->getOtherPlayer($id);
         $this->players->getPlayer($other_player)->setState(\Entity\States::FREE);
         $this->sendToOne($this->players->getSocketById($other_player), Commands::GAME_OVER . Commandee::NO_ID);
         $this->maps->delMap($map_id);
     }
     parent::disconnect($socket);
 }
Example #7
0
 /**
  * Send data to the local WebSocket daemon if active
  */
 private static function sendToWebSocket($queue, $session)
 {
     // Lazy-load the Fake MediaWiki environment and the OD Websocket class from the MediaWiki extension
     if (!defined('WEBSOCKET_VERSION')) {
         require_once __DIR__ . '/WebSocket/WebSocket.php';
         WebSocket::$log = '/var/www/extensions/MediaWiki/WebSocket/ws.log';
         // tmp to match my current daemon
         WebSocket::$rewrite = true;
         WebSocket::setup();
     }
     if (WebSocket::isActive()) {
         // Set the ID of this WebSocket message to the session ID of the sender so the WS server doesn't bounce it back to them
         WebSocket::$clientID = $session;
         // Send queue to all clients
         lgDebug('Sending to WebSocket');
         WebSocket::send('LigminchaGlobal', $queue);
         lgDebug('Sent to WebSocket');
     } else {
         lgDebug('Not sending to WebSocket: not active');
     }
 }
 public function sendMessage($msg)
 {
     $wsmsg = WebSocketMessage::create(json_encode($msg));
     parent::sendMessage($wsmsg);
 }
Example #9
0
 /**
  * Updates the clients presence.
  *
  * @param WebSocket $ws 
  * @param string|null $gamename 
  * @param boolean $idle
  * @return boolean 
  */
 public function updatePresence($ws, $gamename, $idle)
 {
     $idle = $idle == false ? null : true;
     $ws->send(['op' => 3, 'd' => ['game' => !is_null($gamename) ? ['name' => $gamename] : null, 'idle_since' => $idle]]);
     return true;
 }
Example #10
0
function main()
{
    require 'WebSocket.class.php';
    $webSocketServer = new WebSocket();
    //$webSocketServer = Api('WebSocket');
    $onMessage = function ($clientID, $message, $messageLength, $binary) use($webSocketServer) {
        $ip = long2ip($webSocketServer->wsClients[$clientID][6]);
        // check if message length is 0
        if ($messageLength == 0) {
            $webSocketServer->wsClose($clientID);
            return;
        }
        //The speaker is the only person in the room. Don't let them feel lonely.
        if (sizeof($webSocketServer->wsClients) == 1) {
            $webSocketServer->wsSend($clientID, "没有别的人在房间里,但我还是会听你的。——你可靠的服务器");
        } else {
            //Send the message to everyone but the person who said it
            foreach ($webSocketServer->wsClients as $id => $client) {
                if ($id != $clientID) {
                    $webSocketServer->wsSend($id, "游客 {$clientID} ({$ip}) 说 \"{$message}\"");
                }
            }
        }
    };
    $onOpen = function ($clientID) use($webSocketServer) {
        $ip = long2ip($webSocketServer->wsClients[$clientID][6]);
        $webSocketServer->log("{$ip} ({$clientID}) 已连接。");
        //Send a join notice to everyone but the person who joined
        foreach ($webSocketServer->wsClients as $id => $client) {
            if ($id != $clientID) {
                $webSocketServer->wsSend($id, "游客 {$clientID} ({$ip}) 加入房间。");
            }
        }
    };
    $onClose = function ($clientID, $status) use($webSocketServer) {
        $ip = long2ip($webSocketServer->wsClients[$clientID][6]);
        $webSocketServer->log("{$ip} ({$clientID}) 已断开。");
        //Send a user left notice to everyone in the room
        foreach ($webSocketServer->wsClients as $id => $client) {
            $webSocketServer->wsSend($id, "游客 {$clientID} ({$ip}) 离开了房间。");
        }
    };
    $webSocketServer->bind('message', $onMessage);
    $webSocketServer->bind('open', $onOpen);
    $webSocketServer->bind('close', $onClose);
    $serverStatus = $webSocketServer->wsStartServer('0.0.0.0', 9300);
    if ($serverStatus == false) {
        echo $webSocketServer->error;
    } else {
        echo 'webSocketServer Normal end';
    }
}
Example #11
0
$wgHiddenPrefs[] = 'visualeditor-enable';
// don't allow disabling
$wgDefaultUserOptions['visualeditor-enable-experimental'] = 1;
$wgVisualEditorParsoidURL = 'http://localhost:8142';
$wgVisualEditorParsoidPrefix = 'ligmincha';
$wgVisualEditorSupportedSkins[] = 'monobook';
// Organic Design extensions
wfLoadExtension('ExtraMagic');
wfLoadExtension('HighlightJS');
wfLoadExtension('AjaxComments');
$wgAjaxCommentsPollServer = -1;
include "{$IP}/extensions/WebSocket/WebSocket.php";
WebSocket::$log = __DIR__ . '/ws.log';
WebSocket::$rewrite = true;
WebSocket::$ssl_cert = '/etc/letsencrypt/live/ligmincha.com.br/fullchain.pem';
WebSocket::$ssl_key = '/etc/letsencrypt/live/ligmincha.com.br/privkey.pem';
// Make Category:Público public access
$wgHooks['UserGetRights'][] = 'wfPublicCat';
function wfPublicCat()
{
    global $wgWhitelistRead;
    $title = Title::newFromText($_REQUEST['title']);
    if (is_object($title)) {
        $id = $title->getArticleID();
        $dbr = wfGetDB(DB_SLAVE);
        if ($dbr->selectRow('categorylinks', '1', "cl_from = {$id} AND cl_to = 'Público'")) {
            $wgWhitelistRead[] = $title->getPrefixedText();
        }
    }
    return true;
}
Example #12
0
<?php

/*
 **	Echo websocket server (example)
 **
 **	This server returns the same answer as a query
 **
 */
require_once '../src/websocket.class.php';
error_reporting(E_ERROR);
set_time_limit(0);
ob_implicit_flush();
$socket = new WebSocket('tcp://', '127.0.0.1', '7777');
$socket->setOutput('ws-log.txt');
$socket->handler = function ($connection, $data) {
    fwrite($connection, WebSocket::encode($data));
};
$socket->runServer();
Example #13
0
 * @author    jan huang <*****@*****.**>
 * @copyright 2016
 *
 * @link      https://www.github.com/janhuang
 * @link      http://www.fast-d.cn/
 */
include __DIR__ . '/../vendor/autoload.php';
class WebSocket extends \FastD\Swoole\Server\WebSocket
{
    /**
     * @param swoole_websocket_server $server
     * @param swoole_http_request $request
     * @return mixed
     */
    public function doOpen(swoole_websocket_server $server, swoole_http_request $request)
    {
        echo "server: handshake success with fd{$request->fd}\n";
    }
    /**
     * @param swoole_server $server
     * @param swoole_websocket_frame $frame
     * @return mixed
     */
    public function doMessage(swoole_server $server, swoole_websocket_frame $frame)
    {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    }
}
WebSocket::run('ws://0.0.0.0:9527');
Example #14
0
                $resMsg['list'][] = array('fd' => $clid, 'name' => $info['name'], 'avatar' => $info['avatar']);
            }
            $this->send($client_id, json_encode($resMsg));
        } elseif ($msg['cmd'] == 'message') {
            $resMsg = $msg;
            $resMsg['cmd'] = 'fromMsg';
            //表示群发
            if ($msg['channal'] == 0) {
                foreach ($this->connections as $clid => $info) {
                    $this->send($clid, json_encode($resMsg));
                }
            } elseif ($msg['channal'] == 1) {
                $this->send($msg['to'], json_encode($resMsg));
                $this->send($msg['from'], json_encode($resMsg));
            }
        }
    }
    /**
     * 登录时
     */
    function login()
    {
    }
}
$AppSvr = new WebSocket();
$AppSvr->setLogger(new FileLog('runlog'));
//Logger
$server = new TcpServer('0.0.0.0', 9501);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array('worker_num' => 1, 'max_request' => 5000));
#!/php -q
<?php 
// Run from command prompt > php -q websocket.demo.php
// Basic WebSocket demo echoes msg back to client
include "websocket.class.php";
$ws = new WebSocket("localhost", 12345);
$ws->listen();
Example #16
0
        $re = array('mode' => 'wb_send', 'msg' => $msg);
        foreach ($conn_list as $fd) {
            $this->send($fd, json_encode($re));
        }
    }
    function wb_clear($conn_list, $msg)
    {
        $re = array('mode' => 'wb_clear', 'msg' => $msg);
        foreach ($conn_list as $fd) {
            $this->send($fd, json_encode($re));
        }
    }
}
//require __DIR__'/phar://swoole.phar';
Swoole\Config::$debug = true;
Swoole\Error::$echo_html = false;
$AppSvr = new WebSocket();
//$AppSvr->loadSetting(__DIR__."/swoole.ini"); //加载配置文件
$AppSvr->setLogger(new \Swoole\Log\EchoLog(true));
//Logger
/**
 * 如果你没有安装swoole扩展,这里还可选择
 * BlockTCP 阻塞的TCP,支持windows平台
 * SelectTCP 使用select做事件循环,支持windows平台
 * EventTCP 使用libevent,需要安装libevent扩展
 */
$server = new \Swoole\Network\Server('157.7.141.215', 9503);
$server->setProtocol($AppSvr);
$server->daemonize();
//作为守护进程
$server->run(array('worker_num' => 5, 'max_request' => 1000));
Example #17
0
 * WebSocket extension - Allows live connections between the server and other current clients
 *
 * See http://www.organicdesign.co.nz/Extension:WebSocket for details
 * 
 * @file
 * @ingroup Extensions
 * @author Aran Dunkley [http://www.organicdesign.co.nz/aran Aran Dunkley]
 * @copyright © 2015 Aran Dunkley
 * @licence GNU General Public Licence 2.0 or later
 */
if (!defined('MEDIAWIKI')) {
    die('Not an entry point.');
}
define('WEBSOCKET_VERSION', '1.2.1, 2015-04-28');
require __DIR__ . '/WebSocket.class.php';
require __DIR__ . '/WebSocketClient.class.php';
WebSocket::$port = 1729;
# Port the WebSocket daemon will run on
WebSocket::$rewrite = false;
# Configure URL rewriting so that the WebSocket port doesn't need to be public
WebSocket::$perl = '/usr/bin/perl';
# Location of the Perl interpreter
WebSocket::$log = false;
# Set a file location to log WebSocket daemon events and errors
WebSocket::$ssl_cert = false;
# If the wiki uses SSL, then the WebSocket will need to know the certificate file,
WebSocket::$ssl_key = false;
# and the SSL key file
$wgExtensionCredits['other'][] = array('path' => __FILE__, 'name' => 'WebSocket', 'author' => '[http://www.organicdesign.co.nz/aran Aran Dunkley]', 'url' => 'http://www.organicdesign.co.nz/Extension:WebSocket', 'descriptionmsg' => 'websocket-desc', 'version' => WEBSOCKET_VERSION);
$wgExtensionMessagesFiles['WebSocket'] = __DIR__ . '/WebSocket.i18n.php';
new WebSocket();
<?php

// Requires both the WebBrowser and HTTP classes to work.
require_once "support/websocket.php";
require_once "support/web_browser.php";
require_once "support/http.php";
$ws = new WebSocket();
// The first parameter is the WebSocket server.
// The second parameter is the Origin URL.
$result = $ws->Connect("ws://localhost:5578/math/?apikey=123456789101112", "http://localhost");
if (!$result["success"]) {
    var_dump($result);
    exit;
}
// Send a text frame (just an example).
// Get the answer to 5 + 10.
$data = array("pre" => "5", "op" => "+", "post" => "10");
$result = $ws->Write(json_encode($data), WebSocket::FRAMETYPE_TEXT);
// Send a binary frame in two fragments (just an example).
// Get the answer to 5 * 10.
$data["op"] = "*";
$data2 = json_encode($data);
$y = (int) (strlen($data2) / 2);
$result = $ws->Write(substr($data2, 0, $y), WebSocket::FRAMETYPE_BINARY, false);
$result = $ws->Write(substr($data2, $y), WebSocket::FRAMETYPE_BINARY);
// Main loop.
$result = $ws->Wait();
while ($result["success"]) {
    do {
        $result = $ws->Read();
        if (!$result["success"]) {
        $this->send($client_id, 'Server: ' . $ws['message']);
        //$this->broadcast($client_id, $ws['message']);
    }
    function broadcast($client_id, $msg)
    {
        foreach ($this->connections as $clid => $info) {
            if ($client_id != $clid) {
                $this->send($clid, $msg);
            }
        }
    }
}
//require __DIR__'/phar://swoole.phar';
Swoole\Config::$debug = true;
Swoole\Error::$echo_html = false;
$AppSvr = new WebSocket();
$AppSvr->loadSetting(__DIR__ . "/swoole.ini");
//加载配置文件
$AppSvr->setLogger(new \Swoole\Log\EchoLog(true));
//Logger
/**
 * 如果你没有安装swoole扩展,这里还可选择
 * BlockTCP 阻塞的TCP,支持windows平台
 * SelectTCP 使用select做事件循环,支持windows平台
 * EventTCP 使用libevent,需要安装libevent扩展
 */
$enable_ssl = false;
$server = Swoole\Network\Server::autoCreate('0.0.0.0', 9443, $enable_ssl);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array('worker_num' => 1, 'ssl_key_file' => __DIR__ . '/ssl/ssl.key', 'ssl_cert_file' => __DIR__ . '/ssl/ssl.crt'));
<?php

require_once "websocket.client.php";
$input = "Hello World!";
$msg = WebSocketMessage::create($input);
$client = new WebSocket("ws://127.0.0.1:12345/echo/");
$client->open();
$client->sendMessage($msg);
// Wait for an incoming message
$msg = $client->readMessage();
$client->close();
echo $msg->getData();
// Prints "Hello World!" when using the demo.php server