PHP/Network/socket create

Материал из Web эксперт
Версия от 07:06, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating a Simple Socket-Based Server

 
<?php
    set_time_limit(0);
    $address = "127.0.0.1";
    $port = 4545;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_bind($socket, $address, $port);
    socket_listen($socket);
    $connection = socket_accept($socket);
    $result = trim(socket_read($connection, 1024));
    echo "Result received: "$result"\n";
    socket_close($connection);
    socket_shutdown($socket);
    socket_close($socket);
?>



Domain Constants for Socket Connections

 
AF_INET       Internet (IPv4) protocols
 
AF_INET6      Internet (IPv6) protocols
 
AF_UNIX       Local interprocess communication



Retrieving a Website Using Sockets

 
<?php
    $address = "127.0.0.1";
    $port = 80;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($socket, $address, $port);
    socket_write($socket, "GET /index.php HTTP/1.0\n\n");
    $result = "";
    while($read = socket_read($socket, 1024)) {
        $result .= $read;
    }
    echo "Result received: "$result"\n";
    socket_close($socket);
?>



Socket Type Constants

 
SOCK_STREAM        A sequenced and reliable bidirectional connection-based stream. Most common in use. 
 
SOCK_DGRAM         An unreliable, connectionless socket that transmits data of a fixed length. Very good for streaming of data where reliability is not a concern.
 
SOCK_SEQPACKET     Similar to stream sockets, except data is transmitted and received in fixed-length packets.
 
SOCK_RAW           A raw socket connection, useful for performing ICMP (Internet Control Message Protocol) operations such as traces, pings, and so on.
 
SOCK_RDM           A reliable but unsequenced socket similar to that of SOCK_DGRAM.