UDP write to socket and read from socket at the sa

2019-06-10 19:05发布

Server:

<?php
error_reporting(E_ALL | E_STRICT);

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

socket_bind($socket, '192.168.1.7', 11104);

$from = "";
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);
//$buf=socket_read($socket, 2048);

echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
$msg="Sikerult";

//socket_write($socket, $msg, strlen($msg));
socket_sendto($socket, $msg, strlen($msg), 0, '192.168.1.6', 11105);
//socket_close($socket);
?>

Client:

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$result = socket_connect($sock, '192.168.1.6', 11105);
$msg = "Sikerult";
$len = strlen($msg);
//socket_write($sock, $msg, strlen($msg));
socket_sendto($sock, $msg, $len, 0, '192.168.1.7', 11104);
//$buf=socket_read($sock, 2048);
socket_recvfrom($sock, $buf, 12, 0, $from, $port);
echo $buf;
socket_close($sock);
?>

The server receives the data from the client but the client got nothing from the server and not stop running.

标签: php sockets udp
2条回答
2楼-- · 2019-06-10 19:55

I'm assuming that 192.168.1.7:11104 is your server.

In server you need to send packet back to where you've received it from:

//...
$msg="Sikerult";
//...
socket_sendto($socket, $msg, strlen($msg), 0, $from, $port);

In the client you're connecting to itself. You should connect it to server:

$srvIP = '192.168.1.7';
$srvPort = 11104;
$result = socket_connect($sock, $srvIP, $srvPort);
$msg = "Sikerult";
$len = strlen($msg);
socket_send($sock, $msg, $len, 0);
socket_recv($sock, $buf, 12, 0);
查看更多
地球回转人心会变
3楼-- · 2019-06-10 20:02

If it is a UDP socket then why do you need to connect in the first place. Doesn't this suffice?

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

    $msg = "Sikerult";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '192.168.1.7', 11104);

    socket_recvfrom($sock, $buf, 12, 0, '192.168.1.7', 11104);
    echo $buf;

    socket_close($sock);
?>
查看更多
登录 后发表回答