douyan1244
2017-02-17 13:56
浏览 258
已采纳

PHP上的UDP服务器,端口出现问题

Im trying to create a simple UDP server on php which initially will be receiving some dummy data. I've tried following some tutorials and now i can create and bind a socket. However when im using socket_recvfrom for some reason the page just keeps loading and when i refresh it again, the port is taken and i cant bind the socket in that port anymore. below is my code and any answer is welcomed. `

if(!($sock=socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);

die("Couldnt create socket: [$errorcode] $errormsg 
");
}
echo "socket create OK";
if (!socket_bind($sock,"localhost",8880))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);

die("Couldnt bind socket: [$errorcode] $errormsg 
");
 }
echo "socket bind OK";

// while(1)
// {
$remote_ip ='';
$remote_port=0;
echo "waiting for data ... 
";
$r=socket_recvfrom($sock, $buf, 512 , 0 , $remote_ip , $remote_port);
echo "$remote_ip : $remote_port --". $buf;
// }

// socket_close($sock);

图片转代码服务由CSDN问答提供 功能建议

我试图在php上创建一个简单的UDP服务器,最初将接收一些虚拟数据。 我已经尝试过一些教程,现在我可以创建并绑定套接字。 但是,当我使用 socket_recvfrom 由于某种原因,页面只是继续加载,当我再次刷新它时,端口被采取,我不能再绑定该端口中的套接字。 下面是我的代码,欢迎任何答案。

  if(!($ sock = socket_create(AF_INET,SOCK_DGRAM,0)))
 {
 $  errorcode = socket_last_error(); 
 $ errormsg = socket_strerror($ errorcode); 
 
die(“无法创建套接字:[$ errorcode] $ errormsg 
”); 
} 
echo“socket create OK”; \  nif(!socket_bind($ sock,“localhost”,8880))
 {
 $ errorcode = socket_last_error(); 
 $ errormsg = socket_strerror($ errorcode); 
 
die(“无法绑定套接字:[$  errorcode] $ errormsg 
“); 
} 
echo”socket bind OK“; 
 
 // while(1)
 // {
 $ remote_ip =''; 
 $ remote_port = 0;  
echo“等待数据...... 
”; 
 $ r = socket_recvfrom($ sock,$ buf,512,0,$ remote_ip,$ remote_port); 
echo“$ remote_ip:$ remote_port  - ”。  $ buf; 
 //} 
 
 // socket_close($ sock); 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsaf415212 2017-08-06 12:21
    已采纳

    I ended up using this function:

    if (false ===($tcpsock = stream_socket_server("tcp://127.0.0.1:8876",$errorno,$errstr))) echo"tcp socket failed : $errstr($errorno) ";
    if(false ===($connection = stream_socket_accept($tcpsock))) echo "tcp accept failed! "; else echo "tcp accepted";

    And if you want a UDP socket, you just have to :stream_socket_server("udp://127.0.0.1:8876",$errorno,$errstr)))

    点赞 打赏 评论

相关推荐 更多相似问题