PHPでサーバ

TCP

  • TCPヘッダ

http://www.atmarkit.co.jp/ait/articles/0401/29/news080_2.html

  • TCPの状態遷移図

http://www.atmarkit.co.jp/ait/articles/0402/13/news096_3.html

TCP Server

<?php
/**
 * PHP Server Test Program
 * @php.ini extension=php_sockets.dll
 */

$port = 30003;
$sock = socket_create_listen($port);

while (true) {
    echo "--- Listen to Accept --- \n";
    $clientsock = socket_accept($sock);
    echo "--- End Accept --- \n";

    if ($clientsock == false) {
    echo socket_strerror(socket_last_error());
        exit;
    }
    
    while (true) {
        $h = socket_read($clientsock, 1024);
        if ($h === false || $h === "") break;
        echo $h;
    }
    
    socket_close($clientsock);
}

socket_close($sock);

TCP Client

<?php
/**
 * PHP Client Test Program
 * @php.ini extension=php_sockets.dll
 */

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_connect($sock, 'tatenosystem.com', 80);

socket_write($sock, 'GET / HTTP/1.1'."\r\n");
socket_write($sock, 'Host: tatenosystem.com'."\r\n");
socket_write($sock, "\r\n");

while (true) {
    // data read
    $buff = socket_read($sock, 1024);
    if ($buff == "") break;
    echo $buff;
}

socket_close($sock);

UDP

  • UDPのヘッダ

http://www.atmarkit.co.jp/ait/articles/0310/09/news001_3.html

UDP Recive

<?php
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 30003);

$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);
echo $buf .' ('. $from .':'. $port .')'. PHP_EOL;

UDP Send

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = "MY SEND DATA";
socket_sendto($sock, $msg, strlen($msg), 0, '127.0.0.1', 30003);
socket_close($sock);

Sample HTML

<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Hello World</h1>
<img src="test.jpg" />
</body>
</html>