PHP建立socket连接

  • 2016-6-19 23:22
  • PHP二次开发
  • 阅读(2607)
  • 评论(0)
  • 来源:互联网
  • 摘要: server端 ?php //确保在连接客户端时不会超时 set_time_limit(0); //设置IP和端口号 $address = '0.0.0.0'; $port = 2009; //调试的时候,可以多换端口来测试程序! //创建一个SOCKET if (($sock = socket_create(AF ...
    server端

    <?php
    
    //确保在连接客户端时不会超时
    set_time_limit(0);
    
    //设置IP和端口号
    $address = '0.0.0.0';
    $port = 2009;    //调试的时候,可以多换端口来测试程序!
    //创建一个SOCKET
    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
        echo "socket_create() 失败的原因是:" . socket_strerror($sock) . "<br>";
    }
    
    //绑定到socket端口
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        echo "socket_bind() 失败的原因是:" . socket_strerror($ret) . "<br>";
    }
    
    //开始监听
    if (($ret = socket_listen($sock, 4)) < 0) {
        echo "socket_listen() 失败的原因是:" . socket_strerror($ret) . "<br>";
    }
    
    do {
        if (($msgsock = socket_accept($sock)) < 0) {
            echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
            break;
        }
    
    //发到客户端
        $msg = "<font color=red>欢迎进入服务器!</font><br>";
        socket_write($msgsock, $msg, strlen($msg));
    
        echo "读取客户端发来的信息<br>";
        $buf = socket_read($msgsock, 8192);
    
    
        $talkback = "收到的信息:$buf<br>";
        echo $talkback;
    
    
    //echo $buf;
        socket_close($msgsock);
    } while (true);
    
    socket_close($sock);
    ?>


    client端

    <?php
    
    error_reporting(E_ALL);
    set_time_limit(0);
    echo "<h2>TCP/IP Connection</h2>\n";
    
    $service_port = 2009; //服务端端口
    $address = "127.0.0.1"; //服务端IP
    
    
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
        echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
    } else {
        echo "OK.\n";
    }
    
    echo "试图连接 '$address' 端口 '$service_port'...<br>";
    $result = socket_connect($socket, $address, $service_port);
    if ($result < 0) {
        echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
    } else {
        echo "连接OK<br>";
    }
    
    $in = "Hello\r\n";
    $in .= "我是Chester\r\n";
    $out = '';
    $out1 = '';
    
    
    if (!socket_write($socket, $in, strlen($in))) {
        echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
    } else {
        echo "发送到服务器信息成功!<br>";
        echo "发送的内容为:<font color='red'>$in</font> <br>";
    }
    
    while ($out = socket_read($socket, 8192)) {
        echo "接收服务器回传信息成功!<br>";
        echo "接受的内容为:", $out;
    }
    
    
    echo "关闭SOCKET...<br>";
    socket_close($socket);
    echo "关闭OK<br>";
    ?>



    PHP技术交流QQ群:422137578

    除非注明,文章均为 PHP二次开发 原创,转载请注明本文地址:http://www.php2.cc/article-2328-1.html

    相关阅读

    最新评论

    用户名:  *

    邮 箱:  *

    网 址: 注意加上“http://”哦!