PHP Socket编程小试

参考资料:

      PHP官方手册php实例说明 socket通信机制( 张映 )

 

      对于PHP Socket编程,一直感觉很陌生,今天特意了解了一下,根据资料做了个小例子,本地可以运行成功。

服务端:

<?php
/**
 * server端
 * @author flyer0126
 * @since 2012/08/21
 */

set_time_limit(0);

// 加载扩展库
if (!extension_loaded('sockets')){
	if (strtoupper(substr(PHP_OS, 3)) == 'WIN'){
		dl('php_sockets . dll');
	} else{
		dl('sockets . so');
	}
}

// 建立server端socket  
$tcp = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $tcp);  
socket_bind($socket, "127.0.0.1", 20080);       //绑定要监听的端口  
socket_listen($socket);       //监听端口  

//初始化一个数据,和客户端通信  
$buffer = "connect ok";  
while (true) { 
    // 接受一个socket连接  
    $connection = socket_accept($socket);  
    if(!$connection){  
        echo "connect fail";  
    }else{  
            echo "Socket connected\r\n";  
            // 向客户端传递一个信息数据  
            if ($buffer != "") {  
                echo "send data to client\r\n";  
                socket_write($connection, $buffer . "\r\n", strlen($buffer . "\r\n")); 
                echo "Wrote to socket\r\n";  
            } else {  
                echo "no data in the buffer\r\n" ;  
            }  
            // 从客户端取得信息  
            while ($data = @socket_read($connection, 1024, PHP_NORMAL_READ)) {  
                    printf("Buffer: " . $data . "\r\n");  
                    //取得信息给客户端一个反馈  
                    socket_write($connection, "Information Received\r\n", strlen("Information Received\r\n"));  
            }  
    }  
  
    socket_close($connection);  
    //关闭 socket  
    printf("Closed the socket\r\n");  
}

  客户端:

<?php
/**
 * client端
 * @author flyer0126
 * @since 2012/08/21
 */

// 建立客户端的socet连接  
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);  
$connection = socket_connect($socket, '127.0.0.1', 20080);    //连接服务器端socket  

while ($buffer = @socket_read($socket, 1024, PHP_NORMAL_READ)) {  
    //服务端告诉客户端,自己的状态  
    if (preg_match("/not connect/",$buffer)) {  
        echo "don`t connect\r\n";  
        break;  
    } else {  
        //服务器传来信息  
        echo "Buffer Data: " . $buffer . "\r\n";  
  
        echo "Writing to Socket\r\n";  
        // 将客户的信息写到通道中,传给服务器端 
        $write_data = "SOME DATA\r\n";
        if (!socket_write($socket, $write_data)) {  
            echo "Write failed\n";  
        }  
        //服务器端收到信息后,给于的回应信息  
        while ($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)) {  
                echo "sent to server: $write_data, response from server was:" . $buffer . "\r\n";  
        }         
  
    }  
}  

      运行server端,查看端口20080已处于监听状态,另一个命令提示符执行client端,接收处理数据正常。

服务端执行输出:
PHP Socket编程小试_第1张图片
  客户端执行输出:
PHP Socket编程小试_第2张图片

 

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