从udpsocket发送和获取数据

时间:2015-12-08 23:33:45

标签: php sockets

我正在使用服务器列表查看器 有人告诉我,我应该使用UdpSocket将数据发送到主服务器并从中接收数据(在本例中为MW2-IW4游戏)

所以这是你使用的命令或套接字

"\xff\xff\xff\getservers IW4 <MASTERSERVERPORTHERE> full empty\x00"

所以我尝试使用此代码

<?php  
  $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    $msg = "\xff\xff\xff\getservers IW4 <MASTERSERVERPORT> full empty\x00";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, 'MASTERSERVERIP' , 1223);
    socket_close($sock);
?>

但没有收到任何数据,只得到36号...... PS:

i don't know much things about sockets.

2 个答案:

答案 0 :(得分:1)

我想了解如何在不久前做到这一点,并记住这篇文章,如果有人仍然感兴趣,你就是这样做的:

<?php
$ip = "127.0.0.1";
$port = 1337;
$socket = fsockopen('udp://'.$ip, $port);
stream_set_blocking($socket, 0);
stream_set_timeout($socket, 1); //1 = timeout

fwrite($socket, "YOUR UDP COMMAND HERE\n");

$time=time()+1; //1=timeout
$returned = "";
while($time > time()) {
    $returned .= fgets($socket);
}


echo($returned); // the returned value
@fclose($socket); //we are done, so better close it.
?>

答案 1 :(得分:0)

只需使用fsockopen它就容易多了,

$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);

if (!$fp) echo "ERROR: $errno - $errstr<br />\n";

fwrite($fp, "\n");
while (!feof($fp)) {
    echo fgets($fp, 128);
}
fclose($fp);