一直以来,PHP很少用于socket编程,毕竟是一门脚本语言,效率会成为很大的瓶颈,但是不能说PHP就无法用于socket编程,也不能说PHP的socket编程性能就有多么的低,例如知名的一款PHP socket框架 workerman 就是用纯PHP开发,并且号称拥有优秀的性能,所以在某些环境下,PHP socket编程或许也可一展身手。
PHP提供了一系列类似C语言socket库中的方法供我们调用:
socket_accept — Accepts a connection on a socket
socket_bind — 给套接字绑定名字
socket_clear_error — 清除套接字或者最后的错误代码上的错误
socket_close — 关闭套接字资源
socket_cmsg_space — Calculate message buffer size
socket_connect — 开启一个套接字连接
socket_create_listen — Opens a socket on port to accept connections
socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
socket_create — 创建一个套接字(通讯节点)
socket_get_option — Gets socket options for the socket
socket_getopt — 别名 socket_get_option
socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
socket_import_stream — Import a stream
socket_last_error — Returns the last error on the socket
socket_listen — Listens for a connection on a socket
socket_read — Reads a maximum of length bytes from a socket
socket_recv — 从已连接的socket接收数据
socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
socket_recvmsg — Read a message
socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
socket_send — Sends data to a connected socket
socket_sendmsg — Send a message
socket_sendto — Sends a message to a socket, whether it is connected or not
socket_set_block — Sets blocking mode on a socket resource
socket_set_nonblock — Sets nonblocking mode for file descriptor fd
socket_set_option — Sets socket options for the socket
socket_setopt — 别名 socket_set_option
socket_shutdown — Shuts down a socket for receiving, sending, or both
socket_strerror — Return a string describing a socket error
socket_write — Write to a socket
更多细节请查看PHP关于socket的官方手册:http://php.net/manual/zh/book.sockets.php
<?php
$servsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个socket
if (FALSE === $servsock)
{
$errcode = socket_last_error();
fwrite(STDERR, "socket create fail: " . socket_strerror($errcode));
exit(-1);
}
if (!socket_bind($servsock, '127.0.0.1', 8888)) // 绑定ip地址及端口
{
$errcode = socket_last_error();
fwrite(STDERR, "socket bind fail: " . socket_strerror($errcode));
exit(-1);
}
if (!socket_listen($servsock, 128)) // 允许多少个客户端来排队连接
{
$errcode = socket_last_error();
fwrite(STDERR, "socket listen fail: " . socket_strerror($errcode));
exit(-1);
}
while (1)
{
$connsock = socket_accept($servsock); //响应客户端连接
if ($connsock)
{
socket_getpeername($connsock, $addr, $port); //获取连接过来的客户端ip地址和端口
echo "client connect server: ip = $addr, port = $port" . PHP_EOL;
while (1)
{
$data = socket_read($connsock, 1024); //从客户端读取数据
if ($data === '')
{
//客户端关闭
socket_close($connsock);
echo "client close" . PHP_EOL;
break;
}
else
{
echo 'read from client:' . $data;
$data = strtoupper($data); //小写转大写
socket_write($connsock, $data); //回写给客户端
}
}
}
}
socket_close($servsock);
启动这个服务器:
[root@localhost php]# php phptcpserver.php
之后这个服务器就一直阻塞在那里,等待客户端连接,我们可以用telnet命令来连接这个服务器:
[root@localhost ~]# telnet 127.0.0.1 8888
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
ajdjajksdjkaasda
AJDJAJKSDJKAASDA
小明哈哈哈哈笑
小明哈哈哈哈笑
小明efsfsdfsdf了哈哈哈
小明EFSFSDFSDF了哈哈哈
服务器端输出:
[root@localhost php]# php phptcpserver.php
client connect server: ip = 127.0.0.1, port = 50398
read from client:ajdjajksdjkaasda
read from client:小明哈哈哈哈笑
read from client:小明efsfsdfsdf了哈哈哈
但其实这个TCP服务器是有问题的,它一次只能处理一个客户端的连接和数据传输,这是因为一个客户端连接过来后,进程就去负责读写客户端数据,当客户端没有传输数据时,tcp服务器处于阻塞读状态,无法再去处理其他客户端的连接请求了。
解决这个问题的一种办法就是采用多进程服务器,每当一个客户端连接过来,服务器开一个子进程专门负责和该客户端的数据传输,而父进程仍然监听客户端的连接,但是起进程的代价是昂贵的,这种多进程的机制显然支撑不了高并发。
另一个解决办法是使用IO多路复用机制,使用php为我们提供的socket_select方法,它可以监听多个socket,如果其中某个socket状态发生了改变,比如从不可写变为可写,从不可读变为可读,这个方法就会返回,从而我们就可以去处理这个socket,处理客户端的连接,读写操作等等。来看php文档中对该socket_select的介绍
socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
说明
int socket_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )
socket_select() accepts arrays of sockets and waits for them to change status.
Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets.
Three independent arrays of socket resources are watched.
You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead.
Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.
返回值
On success socket_select() returns the number of socket resources contained in the modified arrays,
which may be zero if the timeout expires before anything interesting happens.
On error FALSE is returned. The error code can be retrieved with socket_last_error().
大致翻译下:
socket_select --- 在给定的几组sockets数组上执行 select() 系统调用,用一个特定的超时时间。
socket_select() 接受几组sockets数组作为参数,并监听它们改变状态
这些基于BSD scokets 能够识别这些socket资源数组实际上就是文件描述符集合。
三个不同的socket资源数组会被同时监听。
这三个资源数组不是必传的, 你可以用一个空数组或者NULL作为参数,不要忘记这三个数组是以引用的方式传递的,在函数返回后,这些数组的值会被改变。
socket_select() 调用成功返回这三个数组中状态改变的socket总数,如果设置了timeout,并且在timeout之内都没有状态改变,这个函数将返回0,出错时返回FALSE,可以用socket_last_error() 获取错误码。
使用 socket_select() 优化之前 phptcpserver.php 代码:
<?php
$servsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个socket
if (FALSE === $servsock)
{
$errcode = socket_last_error();
fwrite(STDERR, "socket create fail: " . socket_strerror($errcode));
exit(-1);
}
if (!socket_bind($servsock, '127.0.0.1', 8888)) // 绑定ip地址及端口
{
$errcode = socket_last_error();
fwrite(STDERR, "socket bind fail: " . socket_strerror($errcode));
exit(-1);
}
if (!socket_listen($servsock, 128)) // 允许多少个客户端来排队连接
{
$errcode = socket_last_error();
fwrite(STDERR, "socket listen fail: " . socket_strerror($errcode));
exit(-1);
}
/* 要监听的三个sockets数组 */
$read_socks = array();
$write_socks = array();
$except_socks = NULL; // 注意 php 不支持直接将NULL作为引用传参,所以这里定义一个变量
$read_socks[] = $servsock;
while (1)
{
/* 这两个数组会被改变,所以用两个临时变量 */
$tmp_reads = $read_socks;
$tmp_writes = $write_socks;
// int socket_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )
$count = socket_select($tmp_reads, $tmp_writes, $except_socks, NULL); // timeout 传 NULL 会一直阻塞直到有结果返回
foreach ($tmp_reads as $read)
{
if ($read == $servsock)
{
/* 有新的客户端连接请求 */
$connsock = socket_accept($servsock); //响应客户端连接, 此时不会造成阻塞
if ($connsock)
{
socket_getpeername($connsock, $addr, $port); //获取远程客户端ip地址和端口
echo "client connect server: ip = $addr, port = $port" . PHP_EOL;
// 把新的连接sokcet加入监听
$read_socks[] = $connsock;
$write_socks[] = $connsock;
}
}
else
{
/* 客户端传输数据 */
$data = socket_read($read, 1024); //从客户端读取数据, 此时一定会读到数组而不会产生阻塞
if ($data === '')
{
//移除对该 socket 监听
foreach ($read_socks as $key => $val)
{
if ($val == $read) unset($read_socks[$key]);
}
foreach ($write_socks as $key => $val)
{
if ($val == $read) unset($write_socks[$key]);
}
socket_close($read);
echo "client close" . PHP_EOL;
}
else
{
socket_getpeername($read, $addr, $port); //获取远程客户端ip地址和端口
echo "read from client # $addr:$port # " . $data;
$data = strtoupper($data); //小写转大写
if (in_array($read, $tmp_writes))
{
//如果该客户端可写 把数据回写给客户端
socket_write($read, $data);
}
}
}
}
}
socket_close($servsock);
现在,这个TCP服务器就可以支持多个客户端同时连接了,测试下:
服务器端:
[root@localhost php]# php phptcpserver.php
client connect server: ip = 127.0.0.1, port = 50404
read from client # 127.0.0.1:50404 # hello world
client connect server: ip = 127.0.0.1, port = 50406
read from client # 127.0.0.1:50406 # hello PHP
read from client # 127.0.0.1:50404 # 少小离家老大回
read from client # 127.0.0.1:50404 # 乡音无改鬓毛衰
read from client # 127.0.0.1:50406 # 老当益壮,
read from client # 127.0.0.1:50406 # 宁移白首之心
client close
client connect server: ip = 127.0.0.1, port = 50408
稍微修改上面的服务器返回,返回一个HTTP响应头和一个简单的HTTP响应体,这样就摇身一变成了一个最简单的HTTP服务器:
....
socket_getpeername($read, $addr, $port); //获取远程客户端ip地址和端口
echo "read from client # $addr:$port # " . $data;
$response = "HTTP/1.1 200 OK\r\n";
$response .= "Server: phphttpserver\r\n";
$response .= "Content-Type: text/html\r\n";
$response .= "Content-Length: 3\r\n\r\n";
$response .= "ok\n";
if (in_array($read, $tmp_writes))
{
//如果该客户端可写 把数据回写给客户端
socket_write($read, $response);
socket_close($read); // 主动关闭客户端连接
//移除对该 socket 监听
foreach ($read_socks as $key => $val)
{
if ($val == $read) unset($read_socks[$key]);
}
foreach ($write_socks as $key => $val)
{
if ($val == $read) unset($write_socks[$key]);
}
}
.....
重新启动该服务器,用curl模拟请求该http服务器:
[root@localhost ~]# curl '127.0.0.1:8888'
ok
[root@localhost ~]# curl '127.0.0.1:8888'
ok
[root@localhost ~]# curl '127.0.0.1:8888'
ok
[root@localhost ~]# curl '127.0.0.1:8888'
ok
[root@localhost ~]# curl '127.0.0.1:8888'
ok
[root@localhost ~]#
服务器端输出:
client connect server: ip = 127.0.0.1, port = 50450
read from client # 127.0.0.1:50450 # GET / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Host: 127.0.0.1:8888
Accept: */*
client close
client connect server: ip = 127.0.0.1, port = 50452
read from client # 127.0.0.1:50452 # GET / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Host: 127.0.0.1:8888
Accept: */*
client close
client connect server: ip = 127.0.0.1, port = 50454
read from client # 127.0.0.1:50454 # GET / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Host: 127.0.0.1:8888
Accept: */*
client close
client connect server: ip = 127.0.0.1, port = 50456
read from client # 127.0.0.1:50456 # GET / HTTP/1.1
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Host: 127.0.0.1:8888
Accept: */*
client close
这样一个高并发的HTTP服务器就开发好了,用压测软件测试下并发能力:
看到高达5000多的QPS,有没有小激动呢^^。
PHP是世界上最好的语言 that's all !