【问题标题】:Why does TCP work, when UDP does not?为什么 TCP 可以工作,而 UDP 不行?
【发布时间】:2010-10-16 06:32:24
【问题描述】:

代码:

<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '127.0.0.1';
$port = 11100;

if (($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    do {
    $out = socket_read($msgsock, 2048);

    if (!empty($out)) {
        if ($out == 'quit') {
            break;
        }
        elseif ($out == 'shutdown') {
            socket_write($msgsock, 'plc down', 8);
            socket_close($msgsock);
            break 2;
        }
        else {
            switch ($out) {
                case "KABBE": $response = "Kabbe te!"; break;
                case "SZOPJ": $response = "Szopjal te!"; break;
                default: $response = "Ismeretlen parancs";
            }
            socket_write($msgsock, $response, strlen($response));
            break;
        }
    }
    } while (true);
socket_close($msgsock);
} while (true);

socket_close($sock);
?>

它适用于 TCP:

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

但使用 UDP 时它不起作用:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

错误:

警告:socket_listen() [function.socket-listen]:无法在套接字 [0] 上侦听:所引用的对象类型不支持尝试的操作。在第 22 行的 C:\wamp\www\socket\socket.php socket_listen() 失败:原因:所引用的对象类型不支持尝试的操作。

警告:socket_accept() [function.socket-accept]:无法接受传入连接 [0]:所引用的对象类型不支持尝试的操作。在第 27 行的 C:\wamp\www\socket\socket.php 中 socket_accept() 失败:原因:所引用的对象类型不支持尝试的操作。

【问题讨论】:

    标签: php sockets tcp udp


    【解决方案1】:

    因为 TCP 是面向连接的,而 UDP 不是,并且 UDP 套接字有不同的 API。看看socket_recvfromsocket_sendto

    【讨论】:

      【解决方案2】:

      我已经通过编辑 Growl 类来修复它

       socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port);
      

       socket_sendto($sck, $data, strlen($data), 0x0, $this->address, $this->port);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 2011-04-03
        • 2020-05-20
        • 2013-04-04
        相关资源
        最近更新 更多