博瑞博客

青春是一个充满活力的季节,即便是我们失去了天使的翅膀,只要我们还有一颗青春的心,那么我们的生活依然能够如阳光般灿烂!......
现在位置:首页 > PHP > 使用PHP进行UDP Socket编程

使用PHP进行UDP Socket编程

江湖    PHP    2016-2-26    1123    0评论

本文主要是通过简单的例子介绍下UDP Socket编程.


1.UDP服务器

<?php
//Reduce errors
error_reporting(~E_WARNING);

//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "0.0.0.0" , 11300) ) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

//Do some communication, this loop can handle multiple clients
while(1) {
    echo "Waiting for data ... \n";

    //Receive some data
    $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
    echo "$remote_ip : $remote_port -- " . $buf;

    //Send back the data to the client
    socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
}

socket_close($sock);

在Terminal运行:

$php socket_udp_server.php


Socket created

Socket bind OK

Waiting for data …


2.UDP客户端

<?php
//Reduce errors
error_reporting(~E_WARNING);

$server = '127.0.0.1';
$port = 11300;

if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Communication loop

while(1) {

    //Take some input to send

    echo 'Enter a message to send : ';
    $input = fgets(STDIN);

    //Send the message to the server
    if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port)) {

        $errorcode = socket_last_error();

        $errormsg = socket_strerror($errorcode);

        die("Could not send data: [$errorcode] $errormsg \n");

    }

    //Now receive reply from server and print it

    if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE) {

        $errorcode = socket_last_error();

        $errormsg = socket_strerror($errorcode);

        die("Could not receive data: [$errorcode] $errormsg \n");

    }

    echo "Reply : $reply";
}

在Terminal运行客户端程序:

$php socket_udp_client.php

Socket created

Enter a message to send : udp testonly

Reply : OK udp testonly

Enter a message to send :

 

 

 

 

评论一下分享本文赞助博瑞

赞助博瑞X

扫码赞助博瑞
联系站长
博瑞博客
挤眼亲亲咆哮开心想想可怜糗大了委屈哈哈小声点右哼哼左哼哼疑问坏笑赚钱啦悲伤耍酷勾引厉害握手耶嘻嘻害羞鼓掌馋嘴抓狂抱抱围观威武给力
提交评论

清空信息
关闭评论