UDP 写入套接字并同时从套接字读取
服务器:
<?php
error_reporting(E_ALL | E_STRICT);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 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, '127.0.0.1', 11104);
//socket_close($socket);
?>
客户端:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$result = socket_connect($sock, '127.0.0.1', 11104);
$msg = "Sikerult";
$len = strlen($msg);
//socket_write($sock, $msg, strlen($msg));
socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 11104);
//$buf=socket_read($sock, 2048);
socket_recvfrom($sock, $buf, 12, 0, $from, $port);
echo $buf;
socket_close($sock);
?>
服务器从客户端接收数据,但客户端没有从服务器收到任何数据,并且不停止运行。
Server:
<?php
error_reporting(E_ALL | E_STRICT);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 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, '127.0.0.1', 11104);
//socket_close($socket);
?>
client:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$result = socket_connect($sock, '127.0.0.1', 11104);
$msg = "Sikerult";
$len = strlen($msg);
//socket_write($sock, $msg, strlen($msg));
socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器正在将数据包发送回自身,您需要将其传递给客户端的端口,而不是服务器的端口。 所以:
The server is sending the packet back to itself, you need to pass it the port of the client, not of the server. So: