php简单的服务器/客户端(UDP,数据报)无法看到对方

时间:2011-11-07 21:37:18

标签: php sockets client

服务器:

 $address = '127.0.0.1';
 $port = 46123;
 if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
     echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; die;
 }
 echo 'socket_create OK '.$address.':'.$port."\n";
 if (socket_bind($sock, $address, $port) === false) {
     echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; die;
 }
 if (socket_listen($sock, 5) === false) {
     echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; die;
 }

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

客户端:

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$in = ';lsdkf';
var_dump (socket_sendto($socket, $in,strlen($in), 0,'127.0.0.1',46123));

客户说好,但服务器没有收到消息。我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的服务器实际上不是UDP服务器。取代

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {

if (($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) === false) {

并使用socket_recvfrom代替socket_accept(这对UDP服务器毫无意义)。