PHP socket函数是调用系统的的Socket函数,可以参考C语言的socket函数。
Socket函数:http://php.net/manual/en/book.sockets.php
服务器端:
<?php
//设置脚本运行时间不限制
set_time_limit(0);
$server_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server_socket, '127.0.0.1', '1212');
socket_listen($server_socket, 4);
$server_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server_socket, '127.0.0.1', '1212');
socket_listen($server_socket, 4);
//设置非阻塞模式
socket_set_nonblock($server_socket);
do{
socket_set_nonblock($server_socket);
do{
//当有连接时读入数据,并返回
$msg_socket = socket_accept($server_socket);
if($msg_socket)
{
$buff = socket_read($msg_socket, 1024);
echo "client: ".$buff;
socket_write($msg_socket, $buff);
socket_close($msg_socket);
}
}while(true);
socket_close($server_socket);
$msg_socket = socket_accept($server_socket);
if($msg_socket)
{
$buff = socket_read($msg_socket, 1024);
echo "client: ".$buff;
socket_write($msg_socket, $buff);
socket_close($msg_socket);
}
}while(true);
socket_close($server_socket);
客户端:
1 <?php
2 set_time_limit(0);
3 $client_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
4 socket_connect($client_socket, '127.0.0.1', 1212);
5 if(isset($argv[1]))
6 {
7 $send = 'client value '.$argv[1];
8 }
9 else
10 {
11 $send = "default";
12 }
13 socket_write($client_socket, $send." ");
14 $response = socket_read($client_socket, 1024);
15 echo "server: ".$response;
16 socket_close($client_socket);
3 $client_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
4 socket_connect($client_socket, '127.0.0.1', 1212);
5 if(isset($argv[1]))
6 {
7 $send = 'client value '.$argv[1];
8 }
9 else
10 {
11 $send = "default";
12 }
13 socket_write($client_socket, $send." ");
14 $response = socket_read($client_socket, 1024);
15 echo "server: ".$response;
16 socket_close($client_socket);
分别在CLI模式下运行后如图所示: