gpt4 book ai didi

php - 为什么 TCP 工作,而 UDP 不工作?

转载 作者:可可西里 更新时间:2023-11-01 02:45:06 25 4
gpt4 key购买 nike

代码:

<?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);

错误:

Warning: socket_listen() [function.socket-listen]: unable to listen on socket [0]: The attempted operation is not supported for the type of object referenced. in C:\wamp\www\socket\socket.php on line 22 socket_listen() failed: reason: The attempted operation is not supported for the type of object referenced.

Warning: socket_accept() [function.socket-accept]: unable to accept incoming connection [0]: The attempted operation is not supported for the type of object referenced. in C:\wamp\www\socket\socket.php on line 27 socket_accept() failed: reason: The attempted operation is not supported for the type of object referenced.

最佳答案

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

关于php - 为什么 TCP 工作,而 UDP 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com