当前位置: 首页>>代码示例>>PHP>>正文


PHP socket_create函数代码示例

本文整理汇总了PHP中socket_create函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_create函数的具体用法?PHP socket_create怎么用?PHP socket_create使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了socket_create函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: start

 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);
 }
开发者ID:wispira,项目名称:framework,代码行数:60,代码来源:Server.php

示例2: connect

 /**
  * Connects the TCP socket to the host with the given IP address and port
  * number
  *
  * Depending on whether PHP's sockets extension is loaded, this uses either
  * <var>socket_create</var>/<var>socket_connect</var> or
  * <var>fsockopen</var>.
  *
  * @param string $ipAddress The IP address to connect to
  * @param int $portNumber The TCP port to connect to
  * @param int $timeout The timeout in milliseconds
  * @throws SocketException if an error occurs during connecting the socket
  */
 public function connect($ipAddress, $portNumber, $timeout)
 {
     $this->ipAddress = $ipAddress;
     $this->portNumber = $portNumber;
     if ($this->socketsEnabled) {
         if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
             throw new SocketException(socket_last_error($this->socket));
         }
         socket_set_nonblock($this->socket);
         @socket_connect($this->socket, $ipAddress, $portNumber);
         $write = array($this->socket);
         $read = $except = array();
         $sec = floor($timeout / 1000);
         $usec = $timeout % 1000;
         if (!socket_select($read, $write, $except, $sec, $usec)) {
             $errorCode = socket_last_error($this->socket);
         } else {
             $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR);
         }
         if ($errorCode) {
             throw new SocketException($errorCode);
         }
         socket_set_block($this->socket);
     } else {
         if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) {
             throw new SocketException($socketErrstr);
         }
         stream_set_blocking($this->socket, true);
     }
 }
开发者ID:heartless-gaming,项目名称:game-server-status,代码行数:43,代码来源:TCPSocket.php

示例3: flushAll

 /**
  * {@inheritdoc}
  */
 public function flushAll()
 {
     if ($this->currentOnly) {
         return apc_clear_cache('user') && apc_clear_cache();
     }
     $result = true;
     foreach ($this->servers as $server) {
         if (count(explode('.', $server['ip'])) == 3) {
             $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         } else {
             $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
         }
         // generate the raw http request
         $command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl());
         $command .= sprintf("Host: %s\r\n", $server['domain']);
         if ($server['basic']) {
             $command .= sprintf("Authorization: Basic %s\r\n", $server['basic']);
         }
         $command .= "Connection: Close\r\n\r\n";
         // setup the default timeout (avoid max execution time)
         socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0));
         socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0));
         socket_connect($socket, $server['ip'], $server['port']);
         socket_write($socket, $command);
         $content = '';
         do {
             $buffer = socket_read($socket, 1024);
             $content .= $buffer;
         } while (!empty($buffer));
         if ($result) {
             $result = substr($content, -2) == 'ok';
         }
     }
     return $result;
 }
开发者ID:saberyounis,项目名称:Sonata-Project,代码行数:38,代码来源:ApcCache.php

示例4: getSock

 private function getSock()
 {
     if ($this->sock == NULL) {
         $this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     }
     return $this->sock;
 }
开发者ID:abrander,项目名称:agento-php,代码行数:7,代码来源:Client.php

示例5: __construct

 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}");
 }
开发者ID:ianju,项目名称:PocketMine-MP,代码行数:25,代码来源:RCON.php

示例6: getsock

function getsock($port)
{
    $socket = null;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false || $socket === null) {
        $error = socket_strerror(socket_last_error());
        $msg = "socket create({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        return NULL;
    }
    socket_set_nonblock($socket);
    $res = socket_connect($socket, API_HOST, $port);
    $timeout = 50;
    while ($res === false && $timeout > 0) {
        $err = socket_last_error($socket);
        echo ".";
        if ($timeout > 1 && ($err == 115 || $err == 114)) {
            $timeout--;
            usleep(50);
            $res = socket_connect($socket, API_HOST, $port);
            continue;
        }
        $error = socket_strerror($err);
        $msg = "socket connect({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        socket_close($socket);
        return NULL;
    }
    socket_set_block($socket);
    return $socket;
}
开发者ID:Encel-US,项目名称:cpuminer-multi,代码行数:31,代码来源:local-sample.php

示例7: ircReport

function ircReport($stuff)
{
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
    socket_write($sock, $stuff . "\n");
    socket_close($sock);
}
开发者ID:RoadrunnerWMC,项目名称:ABXD-plugins,代码行数:7,代码来源:init.php

示例8: sendsock

function sendsock($in)
{
    global $config;
    $service_port = $config['sockport'];
    $address = $config['sockhost'];
    if (!function_exists("socket_create")) {
        error_log(date("y-m-d H:i:s") . " 未启用socket模块\n", 3, "error.log");
        return null;
    }
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        error_log(date("y-m-d H:i:s") . "socket_create() failed, reason: " . socket_strerror(socket_last_error()) . "\n", 3, "error.log");
        return null;
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        error_log(date("y-m-d H:i:s") . "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n", 3, "error.log");
        return null;
    }
    socket_write($socket, $in, strlen($in));
    $result = socket_read($socket, 8192);
    $arr = unpack("C*", $result);
    socket_close($socket);
    return $arr;
}
开发者ID:707wk,项目名称:mechanical_parking_system,代码行数:25,代码来源:index.php

示例9: listenForClients

	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);
		}
	}
开发者ID:nard,项目名称:Pushchat-Server,代码行数:28,代码来源:PushService.php

示例10: WakeOnLan

function WakeOnLan($addr, $mac_address, $socket_number)
{
    $addr_byte = explode(':', $mac_address);
    $hw_addr = '';
    for ($a = 0; $a < 6; $a++) {
        $hw_addr .= chr(hexdec($addr_byte[$a]));
        $msg = chr(255) . chr(255) . chr(255) . chr(255) . chr(255) . chr(255);
        for ($a = 1; $a <= 16; $a++) {
            $msg .= $hw_addr;
            // send it to the broadcast address using UDP
            // SQL_BROADCAST option isn't help!!
            $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
            if ($s == false) {
                echo "Error creating socket!\n";
                echo "Error code is '" . socket_last_error($s) . "' - " . socket_strerror(socket_last_error($s));
                return FALSE;
            } else {
                // setting a broadcast option to socket:
                $opt_ret = socket_set_option($s, 1, 6, TRUE);
                if ($opt_ret < 0) {
                    echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
                    return FALSE;
                }
                if (socket_sendto($s, $msg, strlen($msg), 0, $ip_address, $socket_number)) {
                    echo "Magic Packet sent successfully!";
                    socket_close($s);
                    return TRUE;
                } else {
                    echo "Magic packet failed!";
                    return FALSE;
                }
            }
        }
    }
}
开发者ID:guille-phillips,项目名称:vb6misc,代码行数:35,代码来源:wake_on_lan.php

示例11: refresh_user

function refresh_user($discord_id)
{
    global $socket, $error;
    $so = socket_create(AF_UNIX, SOCK_DGRAM, 0);
    if ($so === false) {
        $msg = socket_strerror(socket_last_error());
        $error = "Socket failed: {$msg}";
    } else {
        $res = socket_connect($so, $socket);
        if ($res === false) {
            $msg = socket_strerror(socket_last_error());
            $error = "Connect failed: {$msg}";
        } else {
            $payload = json_encode(array('action' => 'refresh', 'user_id' => $discord_id));
            $res = socket_write($so, $payload);
            if ($res === false) {
                $error = "Socket send failed";
            } else {
                if ($res < strlen($payload)) {
                    $error = "Socket did not send all data";
                }
            }
            socket_shutdown($so);
            socket_close($so);
        }
    }
}
开发者ID:Hornwitser,项目名称:DiscordAuthorizer,代码行数:27,代码来源:forumbot.html.php

示例12: coop_send

function coop_send($message)
{
    if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Couldn't create socket: [{$errorcode}] {$errormsg} \n");
    }
    //Connect socket to remote server
    if (!socket_connect($sock, COOPSERVER, COOPPORT)) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not connect: [{$errorcode}] {$errormsg} \n");
    }
    //Send the message to the server
    if (!socket_send($sock, $message, strlen($message), 0)) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not send data: [{$errorcode}] {$errormsg} \n");
    }
    $buf = 'my buffer';
    if (false !== ($bytes = socket_recv($sock, $buf, 1024, 0))) {
        echo "Read {$bytes} bytes of socket_recv(). close socket ...";
    } else {
        echo "socket_recv() error; Reason: " . socket_strerror(socket_last_error($socket)) . "\n";
    }
    socket_close($sock);
    return $buf;
}
开发者ID:gludie,项目名称:CoopControl,代码行数:28,代码来源:coopclient.php

示例13: create

 /**
  * 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);
 }
开发者ID:vietlethanh,项目名称:KooKooBackEnd,代码行数:12,代码来源:socket.class.php

示例14: get_peers_blocking

 private function get_peers_blocking($info_hash, $host = "router.bittorrent.com", $port = 6881)
 {
     //create a UDP socket to send commands through
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     //Create Command Packet
     $packet = bencode::encode(array("id" => $this->get_unique_node_id(), "info_hash" => hex2bin($info_hash)), array("q" => "get_peers", "t" => $this->unique_id(), "y" => "q"));
     socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);
     //set timeout
     $timeout = array('sec' => 5, 'usec' => 0);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
     $time = time();
     //recieve data
     try {
         socket_recvfrom($socket, $buf, 12000, 0, $host, $port);
     } catch (Exception $e) {
         echo "Error";
         return FALSE;
     }
     //have to manually do the timeout, cant seem to get info from this socket
     if (time() - $time >= 4) {
         socket_close($socket);
         return FALSE;
     }
     //close socket so bad shit don't happen
     socket_close($socket);
     return nodeExtract::return_nodes(bencode::decode($buf));
 }
开发者ID:sharayuS,项目名称:PHP-K-DHT,代码行数:27,代码来源:dht.class.php

示例15: search

 public function search($st = 'ssdp:all', $mx = 2, $man = 'ssdp:discover', $from = null, $port = null, $sockTimout = '2')
 {
     $request = 'M-SEARCH * HTTP/1.1' . "\r\n";
     $request .= 'HOST: 239.255.255.250:1900' . "\r\n";
     $request .= 'MAN: "' . $man . '"' . "\r\n";
     $request .= 'MX: ' . $mx . '' . "\r\n";
     $request .= 'ST: ' . $st . '' . "\r\n";
     $request .= 'USER-AGENT: ' . $this->user_agent . "\r\n";
     $request .= "\r\n";
     $socket = socket_create(AF_INET, SOCK_DGRAM, 0);
     socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, true);
     socket_sendto($socket, $request, strlen($request), 0, '239.255.255.250', 1900);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $sockTimout, 'usec' => '0'));
     $response = array();
     do {
         $buf = null;
         socket_recvfrom($socket, $buf, 1024, MSG_WAITALL, $from, $port);
         if (!is_null($buf)) {
             $data = $this->parseSearchResponse($buf);
             $response[$data['usn']] = $data;
         }
     } while (!is_null($buf));
     socket_close($socket);
     return $response;
 }
开发者ID:T-REX-XP,项目名称:UPnP,代码行数:25,代码来源:Core.php


注:本文中的socket_create函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。