Beispiel #1
0
 /**
  * Accepts incoming connections as they are made.
  */
 private function accept(SocketServer $server) : Generator
 {
     yield from log()->log(Log::INFO, 'NNTP server listening on %s:%d', $server->getAddress(), $server->getPort());
     while ($server->isOpen()) {
         // Wait for a client to connect.
         $socket = (yield from $server->accept());
         // Handle the client in a separate coroutine.
         $coroutine = new Coroutine($this->handleClient($socket));
         $coroutine->done();
     }
 }
Beispiel #2
0
 public function onIdle(SocketServer $server)
 {
     $clients = $server->getClients();
     foreach ($clients as $client) {
         if ($client->buffer) {
             $client->send(array('type' => 'shell', 'result' => $client->buffer));
             $client->buffer = "";
         }
         if ($client->process && !$client->process->isRunning() && !$client->buffer) {
             $client->process = false;
             $client->send(array('type' => 'shell', 'finished' => true));
         }
     }
     usleep(1000 * 10);
 }
Beispiel #3
0
function handle_input(&$server, &$client, $input)
{
    // You probably want to sanitize your inputs here
    $trim = trim($input);
    // Trim the input, Remove Line Endings and Extra Whitespace.
    if (strtolower($trim) == "quit") {
        SocketServer::socket_write_smart($client->socket, "Oh... Goodbye...");
        // Give the user a sad goodbye message, meany!
        $server->disconnect($client->server_clients_index);
        // Disconnect this client.
        return;
        // Ends the function
    }
    $output = strrev($trim);
    // Reverse the String
    SocketServer::socket_write_smart($client->socket, $output);
    // Send the Client back the String
    SocketServer::socket_write_smart($client->socket, "String? ", "");
    // Request Another String
}
    /**
     * Run the server
     * 
     * @return void
     */
    function run()
    {
        global $version;
        $time = strftime("%Y-%m-%d %H:%M:%S");
        $v = $version['string'];
        $motd = <<<EOT
-------------------------------------------------------
|   Welcome to the Mediboard {$this->getServerType()} Server v.{$v}   |
|   Started at {$time}                    |
-------------------------------------------------------

EOT;
        $this->started_datetime = $time;
        $server = $this->server->bind("0.0.0.0", $this->port, $this->certificate, $this->passphrase, $this->certificate_authority);
        $server->setRequestHandler(array($this, "handle"));
        $server->setOnOpenHandler(array($this, "onOpen"));
        $server->setOnCleanupHandler(array($this, "onCleanup"));
        $server->setOnCloseHandler(array($this, "onClose"));
        $server->setOnWriteErrorHandler(array($this, "writeError"));
        $server->run();
    }
function handle_input($server, $client, $input)
{
    $data = trim($input);
    if (strtolower($data) == "quit") {
        // User Wants to quit the server
        SocketServer::socket_write_smart($client->socket, "Oh... Goodbye...");
        // Give the user a sad goodbye message, meany!
        $server->disconnect($client->server_clients_index);
        // Disconnect this client.
        return;
    }
    $deviceId = substr($data, 1, 10);
    $messageCode = substr($data, 11, 2);
    $date = substr($data, 13, 6);
    $time = substr($data, 19, 6);
    $inputVoltage = substr($data, 25, 3);
    $currentLoad = substr($data, 28, 5);
    $status = substr($data, 33, 3);
    $lowCutSetPoint = substr($data, 36, 3);
    $highCutSetPoint = substr($data, 39, 3);
    $overLoadSetPoint = substr($data, 42, 2);
    global $conn;
    $sql = "INSERT INTO audit(device_id, time, date, input_voltage, current_load, status, low_cut_set, high_cut_set, message_code, overload_set) values(" . "'" . $deviceId . "'" . "," . "'" . htmlspecialchars($time) . "'" . "," . "'" . htmlspecialchars($date) . "'" . "," . "'" . htmlspecialchars($inputVoltage) . "'" . "," . "'" . htmlspecialchars($currentLoad) . "'" . "," . "'" . htmlspecialchars($status) . "'" . "," . "'" . htmlspecialchars($lowCutSetPoint) . "'" . "," . "'" . htmlspecialchars($highCutSetPoint) . "'" . "," . "'" . htmlspecialchars($messageCode) . "'" . "," . "'" . htmlspecialchars($overLoadSetPoint) . "'" . ")";
    if ($conn->query($sql) === TRUE) {
        $success = "Auditing Done";
        echo $success;
        ob_flush();
        flush();
    } else {
        $error = "Error: " . $conn->error;
        echo $error;
        ob_flush();
        flush();
    }
    //SocketServer::socket_write_smart($client->socket,$output); // Send the Client back the String
    //SocketServer::socket_write_smart($client->socket,"a? ",""); // Request Another String
}
Beispiel #6
0
function real_time_js_and_php( ) {
   ?> 
<!-- tut 1 -->
   <script type="text/javascript">
      setInterval(function(){
          // inside here, set any data that you need to send to the server
          var some_serialized_data = jQuery('form.my_form').serialize();

          // then fire off an ajax call
          jQuery.ajax({
              url: '/yourPhpScriptForUpdatingData.php',
              success: function(response){
                  // put some javascript here to do something with the 
                  // data that is returned with a successful ajax response,
                  // as available in the 'response' param available, 
                  // inside this function, for example:
                  $('#my_html_element').html(response);
              },
              data: some_serialized_data
          });
      }, 1000); 
      // the '1000' above is the number of milliseconds to wait before running 
      // the callback again: thus this script will call your server and update 
      // the page every second.

   </script>  
<!-- tut 2 -->

  <script type="text/javascript">
    jQuery(function($){
      setInterval(function(){
        $.get( '/getrows.php', function(newRowCount){
          $('#rowcounter').html( newRowCount );
        });
      },5000); // 5000ms == 5 seconds
    });
  </script> 
<!-- tut 3 js.node-->

  <!-- src: http://coenraets.org/blog/2012/10/real-time-web-analytics-with-node-js-and-socket-io/ --> 
<!-- 
    HELPFUL
      src: http://www.dreamincode.net/forums/topic/319049-creating-real-time-web-updates-with-ajax-php-sql-etc/
      AJAX PUSH
      Socket connections 
      sockets. 
      node.js
      database check 
      sockets push
      -->

        <?php

            // Assume this SocketServer is dealing with incomming
            // Socket connections and making them available as
            // "Client" objects through: getClients().
            $server = new SocketServer();

            while ($server->isRunning()) {
              // Go through each of the clients currently connected
              // to the server.
              foreach ($server->getClients() as $client) {
                // If the client has sent a new message to the server
                // receive it and push it down to all the other clients.
                // Then save it in the database.
                if ($client->hasNewData()) {
                  $message = $client->receive();
                  foreach ($server->getClients() as $recipient) {
                    $recipient->send($message);
                  }
                  DB::get()->saveMessage($message);
                }
              } 
              // Sleep for a few milliseconds, just so the process doesn't
              // freeze up the server or eat all it's resources.
              usleep(150000);
            } 
       ?> 
<!-- 
    NOT HELPFUL
      tut 4  
      http://www.webdesignerforum.co.uk/topic/65897-php-mysql-real-time-chat-application-without-javascript/ 
      usleep(250000);

    isset 
--> 
<!-- 
  tut 5   sockets push 
  http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/pushpull.html
  http://socketo.me/docs/push
--> 
   <?php
}
 public function __construct(&$socket, $i)
 {
     $this->server_clients_index = $i;
     $this->socket = socket_accept($socket) or die("Failed to Accept");
     SocketServer::debug("New Client Connected");
     socket_getpeername($this->socket, $ip);
     $this->ip = $ip;
 }
<?php

$serv = new SocketServer();
$serv->run('0.0.0.0', 9504);
class SocketServer
{
    protected $serv;
    //swoole server
    const MAX_PACKAGE_LEN = 8000000;
    //max data accept
    function run($host, $port)
    {
        register_shutdown_function(array($this, 'errorHandler'));
        $this->serv = new swoole_server($host, $port);
        $this->serv->set(array('max_request' => 2000, 'dispatch_mode' => 3, 'worker_num' => 5, 'reactor_num' => 2, 'backlog' => 128, 'open_cpu_affinity' => 1, 'open_tcp_nodelay' => 1, 'tcp_defer_accept' => 5, 'max_conn' => 10000, 'task_worker_num' => 10, 'task_ipc_mode' => 2, 'message_queue_key' => 0x72000100, 'open_length_check' => true, 'package_max_length' => 999999999, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4));
        $this->serv->on('receive', array($this, 'onReceive'));
        $this->serv->on('close', array($this, 'onClose'));
        $this->serv->on('task', array($this, 'onTask'));
        $this->serv->on('finish', array($this, 'onFinish'));
        $this->serv->start();
    }
    function onReceive($serv, $fd, $from_id, $data)
    {
        $packet = json_decode(substr($data, 4), true);
        //todo::包可能解析失败
        $packet["socketfd"] = $fd;
        $task_id = $serv->task(json_encode($packet));
        //todo::任务可能下发失败
    }
    function onTask($serv, $task_id, $from_id, $data)
    {
Beispiel #9
0
<?php

require_once 'includes/tcpConnection.php';
$server = new SocketServer(HOST, PORT);
$server->max_clients = MAX_CLIENTS;
$server->hook("CONNECT", "handle_connect");
$server->hook("INPUT", "handle_input");
$server->infinite_loop();
 public function actionIndex()
 {
     echo "test1";
     $socksvr = new SocketServer();
     $socksvr->restart();
 }
        $this->server = $server;
    }
    public function poll()
    {
    }
    public function connectClient($clientID)
    {
        echo "Client {$clientID} connected.\n";
    }
    public function disconnectClient($clientID, $alive)
    {
        echo "Client {$clientID} disconnected.\n";
    }
}
// Start a server on port 8000
$server = new SocketServer(8000);
// Instantiate our listener and attach it to the server
$listener = new TestListener();
$server->addListener($listener);
// Run the server until killed
while ($server->run()) {
}
/** END EXAMPLE CODE **/
interface ISocketListener
{
    /** 
     * Called for each request received from a client.
     *
     * A "Request" is defined as the data up to a delimiter, as 
     * specified by $server->delimiter, or the complete data that was
     * received from a client before they disconnected.
Beispiel #12
0
 protected function beforeServerLoop()
 {
     parent::beforeServerLoop();
     socket_set_nonblock($this->sockServer);
     pcntl_signal(SIGUSR1, array($this, 'handleProcess'), true);
 }
Beispiel #13
0
#!/usr/local/bin/php
<?php 
require 'minihttpd.php';
require 'upload_handler.php';
function my_exit()
{
    exit;
}
$ss = new SocketServer();
$ss->SetHandler('MiniHTTPD', 'upload_handler');
$ss->Setup();
$pid = pcntl_fork();
if ($pid) {
    pcntl_wait($status);
    print $ss->Port . "\n";
    exit;
} else {
    $pid = pcntl_fork();
    if ($pid) {
        exit;
    } else {
        $ss->Listen();
        try {
            $ss->Run(60, 'my_exit');
            // exit() isn't a real function
        } catch (Exception $e) {
            // I dunno what we done do what where how when stuff what? huh?
        }
    }
}
            unset($this->partial[$clientID]);
            $request['body'] = $data;
        } else {
            $headers = explode("\r\n", $data);
            $status = array_shift($headers);
            list($request['method'], $request['path'], $request['http']) = explode(' ', $status);
            foreach ($headers as $key => $value) {
                list($header, $content) = explode(':', $value, 2);
                $request['headers'][$header] = trim($content);
            }
            if (!in_array($request['method'], array('GET', 'HEAD'))) {
                $this->partial[$clientID] = $request;
                return;
            }
        }
        parent::recvData($clientID, $request, $serverID);
    }
    public function processData($client, $data)
    {
        $client->send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nHello, World!<br>You Requested {$data['path']}\r\n\r\n");
        $client->disconnect();
    }
}
$server = new SocketServer();
$server->setDelimiters("\r\n\r\n");
$id1 = $server->open(8002);
$listener = new HTTPListener();
$server->addListener($listener);
// Run the server until killed
while ($server->run()) {
}
    {
        foreach ($this->clients as $client) {
            call_user_func(array($client, $func), $v1, $v2, $v3, $v4);
        }
    }
}
SetLogFile(dirname($argv[0]) . "/logfile.txt");
LogWrite("############################## Restarted ######################################");
$serverState = ServerState::getInstance();
//LogWrite($serverState->dump());
$LS1 = new LPECListeningSocket($LINN_HOST, $LINN_PORT, 'LPECClientSocket', $serverState, 30000);
$LS2 = new LinnDSListeningSocket(0, 9050, 'LinnDSClientSocket', $serverState, 30000);
$LS2->setLPECListeningSocket($LS1);
//$LS3 = new LinnDSwsListeningSocket(0, 9051, 'LinnDSClientSocket', $serverState, 30000);
//$LS3->setLPECListeningSocket($LS1);
//$LS1->dump();
//$LS2->dump();
//$LS3->dump();
$SS = new SocketServer();
$SS->addListeningSocket($LS1);
$SS->addListeningSocket($LS2);
//$SS->addListeningSocket($LS3);
LogWrite("LinnDS-jukebox-daemon starts...");
try {
    $SS->run();
} catch (Exception $e) {
    LogWrite($e->getMessage());
}
?>

Beispiel #16
0
 /**
  * Does the magic handshake to begin the connection
  *
  * @param string $buffer Buffer sent by the client
  * @return bool Was the handshake successful
  * @throws Exception If something goes wrong
  */
 public function performHandshake($buffer)
 {
     if ($this->state != self::STATE_CONNECTING) {
         throw new Exception('Unable to perform handshake, client is not in connecting state');
     }
     $this->headers = $headers = $this->parseRequestHeader($buffer);
     $key = $headers['Sec-WebSocket-Key'];
     $hash = base64_encode(sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
     $headers = array('HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Accept: ' . $hash);
     $headers = implode("\r\n", $headers) . "\r\n\r\n";
     $left = strlen($headers);
     do {
         $sent = @socket_send($this->socket, $headers, $left, 0);
         if ($sent === false) {
             $error = $this->server->getLastError();
             throw new Exception('Sending handshake failed: : ' . $error->message . ' [' . $error->code . ']');
         }
         $left -= $sent;
         if ($sent > 0) {
             $headers = substr($headers, $sent);
         }
     } while ($left > 0);
     $this->state = self::STATE_OPEN;
 }
    {
        echo $local_message->name . ":" . json_encode($request) . "\n";
        switch ($local_message->name) {
            case "testSimpleRequestResponse":
                if ($request["message"]["subject"] == "ping") {
                    return array("response" => "pong");
                } else {
                    if ($request["message"]["subject"] == "pong") {
                        return array("response" => "ping");
                    }
                }
                break;
            case "testSimpleRequestWithoutParameters":
                return array("response" => "no incoming parameters");
                break;
            case "testNotification":
                break;
            case "testRequestResponseException":
                if ($request["exception"]["cause"] == "callback") {
                    throw new AvroRemoteException(array("exception" => "raised on callback cause"));
                } else {
                    throw new AvroRemoteException("System exception");
                }
                break;
            default:
                throw new AvroRemoteException("Method unknown");
        }
    }
}
$server = new SocketServer('127.0.0.1', 1411, new TestProtocolResponder(AvroProtocol::parse($protocol)), true);
$server->start();
Beispiel #18
0
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 建立失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
        //阻塞模式
        echo "2";
        socket_set_block($this->socket) or die("socket_set_block() 阻塞失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
        //绑定到socket端口
        echo "3";
        $result = socket_bind($this->socket, $this->address, 5062) or die("socket_bind() 绑定失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
        //开始监听
        echo "4";
        $result = socket_listen($this->socket, 4) or die("socket_listen() 监听失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
        echo "Begin listining";
        do {
            // never stop the daemon
            //它接收连接请求并调用一个子连接Socket来处理客户端和服务器间的信息
            $msgsock = socket_accept($this->socket) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
            //读取客户端数据
            echo "Read client data \n";
            //socket_read函数会一直读取客户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符.
            $buf = socket_read($msgsock, 21000);
            echo "Received msg: {$buf}   \n";
            //数据传送 向客户端写入返回结果
            $msg = "welcome \n";
            socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
            //一旦输出被返回到客户端,父/子socket都应通过socket_close($msgsock)函数来终止
            socket_close($msgsock);
        } while (true);
        socket_close($this->socket);
    }
}
$socksvr = new SocketServer();
$socksvr->restart();
<?php

include 'SocketServer.php';
class ProxyListener extends SocketListener
{
    public function processData($client, $data)
    {
        $client->broadcast($data);
    }
}
$server = new SocketServer();
$id1 = $server->open(8002);
$id2 = $server->open(8003);
$listener = new ProxyListener();
$server->addListener($listener);
// Run the server until killed
while ($server->run()) {
}
Beispiel #20
0
 /**
  * @coroutine
  *
  * @param \Icicle\Socket\Server\Server $server
  * @param int $cryptoMethod
  * @param float $timeout
  * @param bool $allowPersistent
  *
  * @return \Generator
  */
 private function accept(SocketServer $server, int $cryptoMethod, float $timeout, bool $allowPersistent) : \Generator
 {
     yield from $this->log->log(Log::INFO, 'HTTP server listening on %s:%d', $server->getAddress(), $server->getPort());
     while ($server->isOpen()) {
         try {
             $coroutine = new Coroutine($this->process(yield from $server->accept(), $cryptoMethod, $timeout, $allowPersistent));
             $coroutine->done(null, $this->onError);
         } catch (Throwable $exception) {
             if ($this->isOpen()) {
                 throw $exception;
             }
         }
     }
 }