dsfhe34889789708 2012-07-24 12:00
浏览 61
已采纳

php cli udp服务器套接字

Below code is my PHP CLi TCP server socket , but I try to make a TCP & UDP socket server or just udp server , but I don't know how can make it

MyCodes:

// PHP SOCKET SERVER
error_reporting(E_ERROR);
// Configuration variables
$host = "192.168.0.1";
$port = 5009;
$max = 20;

// MySQL Database Conf
$db_host ='localhost';
$db_user ='root';
$db_pass ='5222348';
$db_database ='gps';

mysql_connect("$db_host", "$db_user", "$db_pass")or die("################# Can't connet to mysql server");
mysql_select_db("$db_database")or die("################# Can't connet to database");

// --------------------------------
$client = array();

// No timeouts, flush content immediatly
set_time_limit(0);
ob_implicit_flush();

// Server functions
function rLog($msg){
             $msg = "

             echo($msg);

}
// Create socket
// $sock = socket_create(AF_INET,SOCK_DGRAM,0) or die("[".date('Y-m-d H:i:s')."] Could not create socket
");  UDP communication
$sock = socket_create(AF_INET,SOCK_STREAM,0) or die("[".date('Y-m-d H:i:s')."] Could not create socket
");
// Bind to socket
socket_bind($sock,$host,$port) or die("[".date('Y-m-d H:i:s')."] Could not bind to socket
");
// Start listening
socket_listen($sock) or die("[".date('Y-m-d H:i:s')."] Could not set up socket listener
");

rLog("
Server started at ".$host.":".$port."
rev:23-7-11:13");
// Server loop
while(true){
             socket_set_block($sock);
             // Setup clients listen socket for reading
             $read[0] = $sock;
             for($i = 0;$i<$max;$i++){
                          if($client[$i]['sock'] != null)
                                       $read[$i+1] = $client[$i]['sock'];
             }
             // Set up a blocking call to socket_select()
             $ready = socket_select($read,$write = NULL, $except = NULL, $tv_sec = NULL);
             // If a new connection is being made add it to the clients array
             if(in_array($sock,$read)){
                          for($i = 0;$i<$max;$i++){
                                       if($client[$i]['sock']==null){
                                                    if(($client[$i]['sock'] = socket_accept($sock))<0){
                                                                 rLog("socket_accept() failed: ".socket_strerror($client[$i]['sock']));
                                                    }else{
                                                                 socket_getpeername($client[$i]['sock'], $address, $port);
                                                                 rLog("Client #".$i." connected from : ".$address.":".$port."");
                                                    }
                                                    break;
                                       }elseif($i == $max - 1){
                                                    rLog("Too many clients");
                                       }
                          }
                          if(--$ready <= 0)
                          continue;
             }
             for($i=0;$i<$max;$i++){
                          if(in_array($client[$i]['sock'],$read)){
                                       $input = socket_read($client[$i]['sock'],1024);
                                       if($input==null){
                                                    unset($client[$i]);
                                       }
                                       $n = trim($input);
                                       $com = split(" ",$n);
                                       if($n=="EXIT"){
                                                    if($client[$i]['sock']!=null){
                                                                 // Disconnect requested
                                                                 socket_close($client[$i]['sock']);
                                                                 unset($client[$i]['sock']);
                                                                 rLog("Disconnected(2) client #".$i);
                                                                 for($p=0;$p<count($client);$p++){
                                                                              socket_write($client[$p]['sock'],"DISC ".$i.chr(0));
                                                                 }
                                                                 if($i == $adm){
                                                                              $adm = -1;
                                                                 }
                                                    }
                                       }elseif($n=="TERM"){
                                                    // Server termination requested
                                                    socket_close($sock);
                                                    rLog("Terminated server (requested by client #".$i.")");
                                                    exit();
                                       }elseif($input){


                                                    // ----------------------------------------- //
                                                    // $handle = fopen('inbox.txt', 'a+');
                                                    // fwrite($handle, 
                                                        // $input."
".
                                                        // "------------------------------------------------------------
");
                                                    // ########################################################################################### //
                                                    // $input  = "$POS,115316,160137.000,A,2719.9343,N,05310.5553,E,0.00,,180712,,,A/00000,00000/0,0,0,0/794"; // Sample Data
                                                    $input_first = explode(",", $input);

                                                    $frstvalue=$input_first[0];  // $POS            -   Command

                                                    echo $input;
                                                            $handle = fopen('force.log', 'a+');
                                                            fwrite($handle, 
                                                                "Time:[".date('Y-m-d H:i:s')."] , from : ".$address.":".$port."
input: ".$input."
".
                                                                "-------------------------------------------------------------------------------------
");
                                                    ###########################
                                       }
                          }else{

                                       //}
                          }
             }
}
// Close the master sockets
socket_close($sock);

above codes is work perfectly on TCP connections , but can't give UDP requests .

  • 写回答

1条回答 默认 最新

  • doumeng9188 2012-07-24 12:19
    关注

    UDP, being a datagram transport, is a bit different from TCP:

    • Remove call to socket_listen, it's not applicable to UDP.
    • Remove call to socket_accept, same.
    • Use socket_recvfrom to receive datagrams on $sock in a loop.

    That is to say that your original $sock is the data socket, i.e. you only need one here.

    PHP also offers simplified stream_socket_server interface that you can use with a "udp://..." URL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)