コード例 #1
3
ファイル: Server.php プロジェクト: wispira/framework
 public function start()
 {
     $host = $this->host;
     $port = $this->port;
     echo "app can be acessed from ws://{$host}:{$port}\n";
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === false) {
         $this->logLastError($socket, "1");
     }
     if (socket_bind($socket, $host, $port) === false) {
         $this->logLastError($socket, "2");
     }
     if (socket_listen($socket, 5) === false) {
         $this->logLastError($socket, "3");
     }
     $this->setServerSocket($socket);
     $serverSocket = $this->getServerSocket();
     do {
         $sockets = $this->getSockets();
         //Set up a blocking call to socket_select
         $write = null;
         $except = null;
         $tv_sec = 5;
         if (socket_select($sockets, $write, $except, $tv_sec) < 1) {
             continue;
         } else {
             $this->setSockets($sockets);
         }
         //Handle new Connections
         if ($this->hasSocket($serverSocket)) {
             $clientSocket = socket_accept($serverSocket);
             if ($clientSocket === false) {
                 $this->logLastError($serverSocket, "4");
             } else {
                 $this->setClientSocket($clientSocket);
                 $response = "HTTP/1.1 101 Switching Protocols";
                 $this->respond($clientSocket, $response);
             }
         }
         //Handle Input
         foreach ($this->getClientSockets() as $clientSocket) {
             if ($this->hasSocket($clientSocket)) {
                 $message = socket_read($clientSocket, 2048, PHP_NORMAL_READ);
                 if ($message === false) {
                     $this->logLastError($clientSocket, "5");
                     $this->removeSocket($clientSocket);
                     socket_close($clientSocket);
                     break;
                 } else {
                     $message = trim($message);
                     if (!empty($message)) {
                         $response = $this->trigger("message", ["{$message}"]);
                         $this->respond($clientSocket, $response);
                     }
                 }
             }
         }
     } while (true);
     socket_close($serverSocket);
 }
コード例 #2
0
 /**
  * @throws \Exception
  */
 public function bind()
 {
     $socketBind = @socket_bind($this->socket, $this->address, $this->port);
     if (!$socketBind) {
         throw new \Exception('socket could not be bound: ' . '(' . socket_last_error($this->socket) . ') ' . socket_strerror(socket_last_error($this->socket)));
     }
 }
コード例 #3
0
ファイル: Node.php プロジェクト: Waqee/Raft-php
 public function __construct($MyProperties, $NodeList)
 {
     $this->MyProperties = $MyProperties;
     $this->NodeList = $NodeList;
     $this->Sender = new Sender($this->MyProperties);
     $this->Reciever = new Reciever($this->NodeList);
     $this->state = "Initialized";
     $this->currentTerm = 0;
     $this->votedFor = null;
     $this->votes = 0;
     $this->log = array();
     $this->commitIndex = 0;
     $this->lastApplied = 0;
     $this->lastLogIndex = 0;
     $this->nextIndex = array();
     $this->matchIndex = array();
     $this->timeoutinterval = 0.15;
     $this->heartbeatinterval = 0.075;
     $this->LeaderId = null;
     $this->close = false;
     $this->connectIndex = 0;
     set_time_limit(0);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
     socket_bind($this->socket, $MyProperties->ServerAddr, $MyProperties->PortNo + count($NodeList->Nodes) + 1);
     socket_listen($this->socket);
     $this->clientSocket = false;
     socket_set_nonblock($this->socket);
     $this->exiting = false;
     $this->exitcount = 0;
 }
コード例 #4
0
ファイル: CLASS rxnetsvlw.php プロジェクト: roxblnfk/MazePHP
 function lw_start()
 {
     if ($this->Server['Started'] !== false) {
         return false;
     }
     if (($this->Handler = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
         $this->lw_log('socket_create() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     } else {
         $this->lw_log('Socket created');
     }
     socket_set_nonblock($this->Handler);
     if (($ret = socket_bind($this->Handler, $this->Options['Address'], $this->Options['Port'])) !== true) {
         $this->lw_log('socket_bind() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     } else {
         $this->lw_log('Socket bindet');
     }
     if (socket_listen($this->Handler, isset($this->Options['ConnectLimit']) ? $this->Options['ConnectLimit'] : 5) !== true) {
         $this->lw_log('socket_listen() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     }
     //socket_set_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE,2);
     //echo 'SO_KEEPALIVE	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE).RN;
     //echo 'SO_REUSEADDR	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_REUSEADDR).RN;
     //echo 'SO_RCVBUF	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_RCVBUF).RN;
     //echo 'SO_SNDBUF	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_SNDBUF).RN;
     //echo 'SO_DONTROUTE	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_DONTROUTE).RN;
     //echo 'SOCKET_EHOSTUNREACH	: '.SOCKET_EHOSTUNREACH.RN;
     //echo 'SO_BROADCAST : '.socket_get_option($this->Handler,SOL_SOCKET,SO_BROADCAST).RN;
     $this->Server['Started'] = microtime(true);
     /// php 5
     //	wb_create_timer ($_CONTROL['window'], $_SERVER['timer'][0], CL_SOCKET_TIMER);
     return true;
 }
コード例 #5
0
 /**
  * Create a Socket Server on the given domain and port
  * @param $domain String
  * @param $port Float[optional]
  */
 function create($domain, $port = 9801)
 {
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_bind($this->socket, $domain, $port);
     socket_listen($this->socket);
     socket_set_block($this->socket);
 }
コード例 #6
0
ファイル: Server.php プロジェクト: beeyev/Socket
 /**
  * Create server
  *  - bind to port
  *  - listen port
  * @throws ListenException
  * @throws BindException
  */
 function create($blocking = true)
 {
     $this->open();
     $serverSocket = $this->getSocketResource();
     if (!socket_bind($serverSocket, $this->getIp(), $this->getPort())) {
         throw new BindException($this);
     }
     $this->getEventDispatcher()->dispatch(BindEvent::getEventName(), new BindEvent($this, $this));
     if (!socket_listen($serverSocket)) {
         throw new ListenException($this);
     }
     if ($blocking) {
         socket_set_block($serverSocket);
     } else {
         socket_set_nonblock($serverSocket);
     }
     $this->start();
     while ($this->running) {
         $clientSocket = socket_accept($serverSocket);
         if (false == $clientSocket) {
             continue;
         }
         $socket = new Socket($this->getAddressType(), $this->getSocketType(), $this->getTransport(), $this->getEventDispatcher());
         $socket->setSocketResource($clientSocket);
         $socket->getEventDispatcher()->dispatch(NewConnectionEvent::getEventName(), new NewConnectionEvent($socket, $this));
     }
 }
コード例 #7
0
ファイル: WebSocket.php プロジェクト: rubensm1/basic
 /**
  * Começa a escutar conexões e processar as demais funcionalidades
  * @param int $port número da porta
  * @throws EndPointException
  */
 public function listen($port)
 {
     $this->port = $port;
     /* @var resource cria o socket que escutará conexões */
     $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP'));
     if (!socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
         echo socket_strerror(socket_last_error($this->serverSocket));
         exit;
     }
     /* seta o host e a porta */
     if (!@socket_bind($this->serverSocket, 0, $this->port)) {
         throw new EndPointException("socket_bind() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
     }
     /* inicia a escuta de conexões */
     if (!@socket_listen($this->serverSocket)) {
         throw new EndPointException("socket_listen() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
     }
     /* cria um array de sockets e adiciona o serverSocket no array */
     $this->sockets = array($this->serverSocket);
     $this->loopPrincipal();
     /* Fecha todos os sockets e encerra a aplicação */
     foreach ($this->sockets as $socket) {
         if (get_resource_type($socket) == "Socket") {
             socket_close($socket);
         }
     }
 }
コード例 #8
0
ファイル: server.php プロジェクト: webdes83/codeigniter-demos
 public function udp()
 {
     set_time_limit(0);
     $ip = '127.0.0.1';
     $port = 9527;
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     socket_bind($socket, $ip, $port);
     $mem = init_mem();
     if ($mem == false) {
         return;
     }
     while (true) {
         socket_recvfrom($socket, $content, 1024, 0, $ip, $port);
         if (empty($content)) {
             continue;
         }
         //$this->log_data($content);
         $minute = (int) date("i");
         $datagram = $mem->get('datagram');
         if (empty($datagram)) {
             $datagram = array();
         }
         $datagram[$minute][] = $content;
         $mem->set('datagram', $datagram);
     }
     socket_close($socket);
     $mem->close();
 }
コード例 #9
0
ファイル: server.php プロジェクト: baronpig/socket-mutli-chat
 private function createSocket()
 {
     $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, 0);
     socket_bind($this->serverSocket, 0, $this->port) or die("bind error !!");
     socket_listen($this->serverSocket);
     $this->waitSocket();
 }
コード例 #10
0
 public function start()
 {
     self::$_logger->info('Server starts.');
     // Init a non-blocking TCP socket for listening
     $this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (!$this->_sock) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket create error: {$errstr} ({$errno})");
         die;
     }
     socket_set_nonblock($this->_sock);
     if (!socket_bind($this->_sock, $this->_addr, $this->_port)) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket bind error: {$errstr} ({$errno})");
         die;
     }
     if (!socket_listen($this->_sock, $this->_listenQueue)) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket listen error: {$errstr} ({$errno})");
         die;
     }
     // For the listening socket, we use raw event to handle it.
     $this->_listenEvent = event_new();
     event_set($this->_listenEvent, $this->_sock, EV_READ | EV_PERSIST, array($this, 'handleAcceptEvent'));
     event_base_set($this->_listenEvent, $this->_eventBase);
     event_add($this->_listenEvent);
     // Endless loop
     $this->_started = TRUE;
     event_base_loop($this->_eventBase);
     // The loop ends here.
     $this->stop();
 }
コード例 #11
0
ファイル: SocketServer.php プロジェクト: song-yuan/wymenujp
 public function start()
 {
     //确保在连接客户端时不会超时
     echo "1";
     set_time_limit(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);
 }
コード例 #12
0
 public function bind_socket()
 {
     if (socket_bind($this->sock, $this->address, $this->port) === false) {
         return false;
     }
     return true;
 }
コード例 #13
0
/**
 * Creates a server socket and listens for incoming client connections
 * @param string $address The address to listen on
 * @param int $port The port to listen on
 */
function server_loop($address, $port)
{
    global $__server_listening;
    if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
        echo "failed to create socket: " . socket_strerror($sock) . "\n";
        exit;
    }
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        echo "failed to bind socket: " . socket_strerror($ret) . "\n";
        exit;
    }
    if (($ret = socket_listen($sock, 0)) < 0) {
        echo "failed to listen to socket: " . socket_strerror($ret) . "\n";
        exit;
    }
    socket_set_nonblock($sock);
    echo "waiting for clients to connect\n";
    while ($__server_listening) {
        $connection = @socket_accept($sock);
        if ($connection === false) {
            usleep(100);
        } elseif ($connection > 0) {
            handle_client($sock, $connection);
        } else {
            echo "error: " . socket_strerror($connection);
            die;
        }
    }
}
コード例 #14
0
ファイル: phpUPnP.class.php プロジェクト: nemiah/fheME
 public function mServer()
 {
     $sock = socket_create(AF_INET, SOCK_DGRAM, getprotobyname('udp'));
     $mIP = '239.255.255.250';
     if (!socket_bind($sock, $mIP, 1900)) {
         $errorcode = socket_last_error();
         $errormsg = socket_strerror($errorcode);
         die("Could not bind socket : [{$errorcode}] {$errormsg} \n");
     }
     socket_set_option($sock, IPPROTO_IP, MCAST_JOIN_GROUP, array("group" => '239.255.255.250', "interface" => 0));
     while (1) {
         echo "Waiting for data ... \n";
         socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
         echo "{$remote_ip} : {$remote_port} -- " . $buf;
         $query = $this->parseHeaders($buf);
         if (!isset($query["m-search"])) {
             continue;
         }
         $response = "HTTP/1.1 200 OK\r\n";
         $response .= "CACHE-CONTROL: max-age=1810\r\n";
         $response .= "DATE: " . date("r") . "\r\n";
         $response .= "EXT:\r\n";
         $response .= "LOCATION: http://192.168.7.123:9000/TMSDeviceDescription.xml\r\n";
         $response .= "SERVER: Linux/3.x, UPnP/1.1, fheME/0.6\r\n";
         $response .= "ST: urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
         $response .= "USN: uuid:f6da16ab-0d1b-fe1c-abca-82aacf4afcac::urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
         $response .= "Content-Length: 0\r\n";
         $response .= "\r\n";
         //Send back the data to the client
         socket_sendto($sock, $response, strlen($response), 0, $mIP, $remote_port);
     }
     socket_close($sock);
 }
コード例 #15
0
 public function init()
 {
     if ($this->initialized) {
         return NULL;
     }
     $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false) {
         $this->setError($this->getSocketError("Failed creating socket"), LOG_ERR);
         return false;
     }
     if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
         $this->setError($this->getSocketError("Failed setting SO_REUSEADDR on socket"), LOG_ERR);
         return false;
     }
     if (!@socket_bind($this->socket, $this->server_address, $this->server_port)) {
         $this->setError($this->getSocketError("Failed binding socket to " . $this->server_address . ":" . $this->server_port), LOG_ERR);
         return false;
     }
     if (!@socket_listen($this->socket, 5)) {
         $this->setError($this->getSocketError("Failed starting to listen on socket"), LOG_ERR);
         return false;
     }
     socket_set_nonblock($this->socket);
     return $this->initialized = true;
 }
コード例 #16
0
ファイル: xServer.class.php プロジェクト: ben-duffin/xServer
 function __construct($host, $port, $root_pw = false)
 {
     ob_start();
     $this->admin_id = false;
     $this->host = $host;
     $this->port = $port;
     if ($root_pw === false) {
         $this->root_pw = uniqid();
     } else {
         $this->root_pw = $root_pw;
     }
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     if (!is_resource($socket)) {
         $this->console("socket_create() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     if (!socket_bind($socket, $this->host, $this->port)) {
         $this->console("socket_bind() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     if (!socket_listen($socket, 20)) {
         $this->console("socket_listen() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     $this->master = $socket;
     $this->sockets = array($socket);
     $this->mem = new Memcached();
     $this->mem->addServer('127.0.0.1', 11211, 1);
     $this->mem->set('notification-stack', array());
 }
コード例 #17
0
ファイル: jaxl.httpd.php プロジェクト: pavl00/Kalkun
 function __construct($options)
 {
     $this->reset($options);
     pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown"));
     pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown"));
     $options = getopt("p:b:");
     foreach ($options as $opt => $val) {
         switch ($opt) {
             case 'p':
                 $this->settings['port'] = $val;
                 break;
             case 'b':
                 $this->settings['maxq'] = $val;
             default:
                 break;
         }
     }
     $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($this->httpd, 0, $this->settings['port']);
     socket_listen($this->httpd, $this->settings['maxq']);
     $this->id = $this->getResourceID($this->httpd);
     $this->clients = array("0#" . $this->settings['port'] => $this->httpd);
     echo "JAXLHTTPd listening on port " . $this->settings['port'] . PHP_EOL;
 }
コード例 #18
0
ファイル: sockets_server.php プロジェクト: raj4126/twextra
 function connect()
 {
     //set_time_limit(0);
     // create low level socket
     if (!($socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
         trigger_error('Error creating new socket.', E_USER_ERROR);
     }
     // bind socket to TCP port
     if (!socket_bind($socket, $this->host, $this->port)) {
         trigger_error('Error binding socket to TCP port.', E_USER_ERROR);
     }
     // begin listening connections
     if (!socket_listen($socket)) {
         trigger_error('Error listening socket connections.', E_USER_ERROR);
     }
     // create communication socket
     if (!($comSocket = socket_accept($socket))) {
         trigger_error('Error creating communication socket.', E_USER_ERROR);
     }
     // read socket input
     //while ( 1 ) {
     $socketInput = socket_read($comSocket, 1024);
     // convert to uppercase socket input
     $socketOutput = strtoupper(trim($socketInput)) . "n";
     // write data back to socket server
     if (!socket_write($comSocket, $socketOutput, strlen($socketOutput))) {
         trigger_error('Error writing socket output', E_USER_ERROR);
     }
     //}
     // close sockets
     socket_close($comSocket);
     socket_close($socket);
 }
コード例 #19
0
 /**
  * Configures php environment, creates and binds network socket.
  *
  */
 public function __construct()
 {
     set_time_limit(0);
     error_reporting(E_ERROR);
     $this->_socket = socket_create(AF_INET, SOCK_STREAM, 0);
     socket_bind($this->_socket, $this->_host, $this->_port);
 }
コード例 #20
0
function create_connection($host, $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!is_resource($socket)) {
        echo 'Unable to create socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket created.\n";
    }
    if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
        echo 'Unable to set option on socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Set options on socket.\n";
    }
    if (!socket_bind($socket, $host, $port)) {
        echo 'Unable to bind socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket bound to port {$port}.\n";
    }
    if (!socket_listen($socket, SOMAXCONN)) {
        echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error());
    } else {
        echo "Listening on the socket.\n";
    }
    while (true) {
        $connection = @socket_accept($socket);
        if ($connection) {
            echo "Client {$connection} connected!\n";
            send_data($connection);
        } else {
            echo "Bad connection.";
        }
    }
}
コード例 #21
0
ファイル: ModbusMaster.php プロジェクト: bitclaw/phpmodbus
 /**
  * connect
  *
  * Connect the socket
  *
  * @return bool
  */
 private function connect()
 {
     // Create a protocol specific socket
     if ($this->socket_protocol == "TCP") {
         // TCP socket
         $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     } elseif ($this->socket_protocol == "UDP") {
         // UDP socket
         $this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     } else {
         throw new \Exception("Unknown socket protocol, should be 'TCP' or 'UDP'");
     }
     // Bind the client socket to a specific local port
     if (strlen($this->client) > 0) {
         $result = socket_bind($this->sock, $this->client, $this->client_port);
         if ($result === false) {
             throw new \Exception("socket_bind() failed.</br>Reason: ({$result})" . socket_strerror(socket_last_error($this->sock)));
         } else {
             $this->status .= "Bound\n";
         }
     }
     // Connect the socket
     $result = @socket_connect($this->sock, $this->host, $this->port);
     if ($result === false) {
         throw new \Exception("socket_connect() failed.</br>Reason: ({$result})" . socket_strerror(socket_last_error($this->sock)));
     } else {
         $this->status .= "Connected\n";
         return true;
     }
 }
コード例 #22
0
ファイル: ServerImpl.php プロジェクト: Halayem/ANYEM
 public static function start()
 {
     if (self::$_initialized === TRUE) {
         $fatalMsg = "server was already initialized";
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::init();
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === FALSE) {
         $fatalMsg = "socket_create, reason : " . socket_strerror(socket_last_error());
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket created successfully...");
     $r = socket_bind($socket, self::$_server_addr, self::$_server_port);
     if ($r === FALSE) {
         $fatalMsg = "socket_bind, reason : " . socket_strerror(socket_last_error($socket));
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket binded successfully...");
     $r = socket_listen($socket, self::$_max_backlog);
     if ($r === FALSE) {
         $fatalMsg = "socket_listen, reason : " . socket_strerror(socket_last_error($socket));
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket listening successfully...");
     self::$_socket = $socket;
     self::server();
     self::$_log->info("server started successfully...");
 }
コード例 #23
0
ファイル: wikihttpd.php プロジェクト: ahastudio/moniwiki
 function simple_server($address = 0, $port = 8080, $root = 'htdocs')
 {
     @set_time_limit(0);
     $this->document_root = $root;
     if ($this->pre_init() === false) {
         return false;
     }
     if (($this->socket = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
         return false;
     }
     if (@socket_bind($this->socket, $address, $port) < 0) {
         return false;
     }
     if (@socket_listen($this->socket, 5) < 0) {
         return false;
     }
     #    $this->error_handle = @fopen($this->error_file, "a");
     #    if(!$this->error_handle)
     #      return false;
     #    $this->log_handle = @fopen($this->log_file, "a");
     #    if(!$this->log_handle)
     #      return false;
     if ($this->post_init() === false) {
         return false;
     }
     register_shutdown_function(array(&$this, 'close'));
     return $this->running = true;
 }
コード例 #24
0
 public function __construct($logger, $port, $serverip, $serverport)
 {
     $this->logger = $logger;
     $this->port = $port;
     $this->serverip = gethostbyname($serverip);
     $this->serverport = $serverport;
     $this->sendsocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     if (@socket_bind($this->sendsocket, "0.0.0.0", $port) === true) {
         $this->logger->debug("socket open (0.0.0.0 : " . $port . ")");
         $this->logger->info("クライアントから受信したものはすべて " . $serverip . " : " . $serverport . " に送信されます。");
         socket_set_nonblock($this->sendsocket);
     } else {
         $this->working = false;
         $this->logger->info("SendSocketError.(" . $port . ")");
     }
     $this->receivesocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     $port++;
     if (@socket_bind($this->receivesocket, "0.0.0.0", $port) === true) {
         $this->logger->debug("socket open (0.0.0.0 : " . $port . ")");
         socket_set_nonblock($this->receivesocket);
     } else {
         $this->working = false;
         $this->logger->info("ReceiveSocketError.(" . $port . ")");
     }
     $this->packetanalyze = new PacketAnalyze($this->logger);
     $this->receiveips = [];
 }
コード例 #25
0
ファイル: MasterSocket.php プロジェクト: emayk/php-shellout
 /**
  * Bind the socket to the address specified in the options
  * 
  * @return Socket the current object, for chaning
  */
 public function bind()
 {
     if (!socket_bind($this->socket, $this->options['address'], $this->options['port'])) {
         throw new SocketException();
     }
     return $this;
 }
コード例 #26
0
ファイル: server.php プロジェクト: jasper2007111/notes
 private function await()
 {
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($sock < 0) {
         echo "Error:" . socket_strerror(socket_last_error()) . "\n";
     }
     $ret = socket_bind($sock, $this->ip, $this->port);
     if (!$ret) {
         echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n";
         exit;
     }
     echo "OK\n";
     $ret = socket_listen($sock);
     if ($ret < 0) {
         echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n";
     }
     do {
         $new_sock = null;
         try {
             $new_sock = socket_accept($sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
         try {
             $request_string = socket_read($new_sock, 1024);
             $response = $this->output($request_string);
             socket_write($new_sock, $response);
             socket_close($new_sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
     } while (TRUE);
 }
コード例 #27
0
ファイル: PushService.php プロジェクト: nard/Pushchat-Server
	function listenForClients()
	{
		$this->serviceConnection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		socket_bind($this->serviceConnection, $this->serviceHost, $this->servicePort);
		socket_listen($this->serviceConnection, 10);
		
		echo 'LISTENING ',$this->servicePort,"\n";
		
		while($clientSocket = socket_accept($this->serviceConnection))
		{
			socket_write($clientSocket, "OK\n");
			
			$deviceToken = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ));
			$message = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ));
			
			if(!empty($deviceToken) && !empty($message))
			{

				$this->sendNotification($deviceToken, $message);
				socket_write($clientSocket, "SENT\n");
			}
			else
			{
				socket_write($clientSocket, "ERROR\n");
			}
			socket_close($clientSocket);
		}
	}
コード例 #28
0
function server_loop($address, $port)
{
    global $__server_listening;
    // AF_UNIX AF_INET
    if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
        events("failed to create socket: " . socket_strerror($sock), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        events("failed to bind socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_listen($sock, 0)) < 0) {
        events("failed to listen to socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    socket_set_nonblock($sock);
    events(count($GLOBALS["LOCAL_DOMAINS"]) . " internals domains...", __FUNCTION__, __LINE__);
    events("waiting for clients to connect", __FUNCTION__, __LINE__);
    while ($__server_listening) {
        $connection = @socket_accept($sock);
        if ($connection === false) {
            if ($GLOBALS["DebugArticaFilter"] == 1) {
                events("sleep", __FUNCTION__, __LINE__);
            }
            usleep(2000000);
        } elseif ($connection > 0) {
            handle_client($sock, $connection);
        } else {
            events("error: " . socket_strerror($connection), __FUNCTION__, __LINE__);
            die;
        }
    }
}
コード例 #29
0
ファイル: RCON.php プロジェクト: ianju/PocketMine-MP
 public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50)
 {
     $this->server = $server;
     $this->workers = [];
     $this->password = (string) $password;
     $this->server->getLogger()->info("Starting remote control listener");
     if ($this->password === "") {
         $this->server->getLogger()->critical("RCON can't be started: Empty password");
         return;
     }
     $this->threads = (int) max(1, $threads);
     $this->clientsPerThread = (int) max(1, $clientsPerThread);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) {
         $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error()));
         $this->threads = 0;
         return;
     }
     socket_set_block($this->socket);
     for ($n = 0; $n < $this->threads; ++$n) {
         $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread);
     }
     socket_getsockname($this->socket, $addr, $port);
     $this->server->getLogger()->info("RCON running on {$addr}:{$port}");
 }
コード例 #30
0
 function connect()
 {
     set_time_limit(0);
     fscanf(STDIN, "%d\n", $close);
     //listens for the exit command as a boolean but represented as an integer "1"
     while ($close != 1) {
         // create low level socket
         if (!($socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
             trigger_error('Error creating new socket.', E_USER_ERROR);
         }
         // bind socket to TCP port
         if (!socket_bind($socket, $this->host, $this->port)) {
             trigger_error('Error binding socket to TCP port.', E_USER_ERROR);
         }
         // begin listening connections
         if (!socket_listen($socket)) {
             trigger_error('Error listening socket connections.', E_USER_ERROR);
         }
         // create communication socket
         if (!($comSocket = socket_accept($socket))) {
             trigger_error('Error creating communication socket.', E_USER_ERROR);
         }
         // read socket input
         $socketInput = socket_read($comSocket, 1024);
         // convert to uppercase socket input
         $socketOutput = strtoupper(trim($socketInput)) . "n";
         // write data back to socket server
         if (!socket_write($comSocket, $socketOutput, strlen($socketOutput))) {
             trigger_error('Error writing socket output', E_USER_ERROR);
         }
     }
     close($socket, $comSocket);
 }