PHP/Network/socket create

Материал из Web эксперт
Перейти к: навигация, поиск

Creating a Simple Socket-Based Server

    $address = "";
    $port = 4545;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_bind($socket, $address, $port);
    $connection = socket_accept($socket);
    $result = trim(socket_read($connection, 1024));
    echo "Result received: "$result"\n";

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

    $address = "";
    $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 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.