php中的socket

之前研究过php中的socket,但研究到一半就没继续下去了,今日在逛php.net时无意中看到了socket的介绍,闲来无事就又研究了一次。

具体原理还是不很清晰,看过其它人的文章http://blog.51yip.com/php/673.html,照抄了下来,在浏览器中运行,总是有错误,后来看了http://blog.csdn.net/21aspnet/article/details/7412400,才明白,测试环境不应该在浏览器,而是在cmd命令行中,很简单的事例,大家看都会明白,但只有自己动手去做了一遍才会发现问题,进而通过Google,Baidu去搜索答案,继而解决问题,我相信这也是大多人解决问题的做法。

以下是个人在实践的过程中的一些总结。

环境:wamp,路径:D:/wamp,php.ini开启extension=php_sockets.dll

项目路径:D:/wamp/www/lab/

测试步骤:D:\wamp\bin\php\php5.3.13

开始->cmd->进入到D:/wamp/bin/php/php5.3.13

a)执行php.exe D:wamp/www/lab/server.php

b)执行php.exe D:wamp/www/lab/client.php

server.php代码:

<?php
/**
 * 建立Socket服务器端
*/
$tcp = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $tcp); //创建socket
socket_bind($socket, '127.0.0.1', 4096); //绑定地址和端口
socket_listen($socket); //监听端口
//初始化数据
$buffer = "connect";
while(true){
    //接受一个socket连接
    $connect = socket_accept($socket);
    if(!$connect){
        echo "Socket connect is failed!";
    } else {
        //向客户端发送数据
        echo "Socket connected!\n";
        if($buffer != ""){
            echo "send data to client \n";
            socket_write($connect, $buffer . "\n");
            echo "wrote to socket!\n";
        }
        while ($data = @socket_read($connect, 1024, PHP_NORMAL_READ)) {
            printf("Buffer:".$data."\n");
            socket_write($connect, "data receview!\n");
        }
    }
    socket_close($connect);
    printf("close the socket connection!\n");
}

client.php代码:

<?php
/**
* 建立客户端的socket连接
*
*/
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connect = socket_connect($socket, '127.0.0.1', 4096);
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)){
    if(preg_match('/not connect/', $buffer)){
        echo "don't connect \n";
        break;
    } else {
        //服务器端传来消息
        echo "Buffer Data:" . $buffer . "\n";
        //write to socket
        echo "writing to socket!\n";
        if(!socket_write($socket, "some data\n")){
            echo "write to socket failed!\n";
        }
        while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)){
            echo "revice some data:" . $buffer ."\n";
        }
    }
}

在测试过程中,发现:

1.socket_write($socket, "some data\n"),若不加"\n"就发送不成功,原因不明。


测试成功后,接下来测试用html5的socket API与php通信,做一个聊天室应用,应该挺好玩的。哈哈・・・


214430446.png

214435788.png

214442463.png

214449825.png



你可能感兴趣的:(Web,PHP,socket)