PHP 与 网络编程

来自PHP百科全书
跳转至: 导航搜索

创建一个TCP客户端

$fp = stream_socket_client("tcp://192.168.1.100:8080", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}

创建一个TCP服务器端

$socket = stream_socket_server("tcp://0.0.0.0:8080", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, "hello world\n");
    fclose($conn);
  }
  fclose($socket);
}

创建一个UDP客户端

$fp = stream_socket_client("udp://192.168.1.100:8090", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "hello world\n");
    echo fread($fp, 8192);
    fclose($fp);
}

创建一个UDP服务器端

$socket = stream_socket_server("udp://0.0.0.0:8090", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    die("$errstr ($errno)");
}

do {
    $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
    echo "$peer\n";
    stream_socket_sendto($socket, "hello world\n", 0, $peer);
} while ($pkt !== false);