网络Socket及IO多路复用

一直以来,PHP很少用于socket编程,毕竟是一门脚本语言,效率会成为很大的瓶颈,但是不能说PHP就无法用于socket编程,也不能说PHP的socket编程性能就有多么的低,例如知名的一款PHP socket框架 workerman 就是用纯PHP开发,并且号称拥有优秀的性能,所以在某些环境下,PHP socket编程或许也可一展身手。

PHP提供了一系列类似C语言socket库中的方法供我们调用:

 

  1. socket_accept — Accepts a connection on a socket
  2. socket_bind — 给套接字绑定名字
  3. socket_clear_error — 清除套接字或者最后的错误代码上的错误
  4. socket_close — 关闭套接字资源
  5. socket_cmsg_space — Calculate message buffer size
  6. socket_connect — 开启一个套接字连接
  7. socket_create_listen — Opens a socket on port to accept connections
  8. socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
  9. socket_create — 创建一个套接字(通讯节点)
  10. socket_get_option — Gets socket options for the socket
  11. socket_getopt — 别名 socket_get_option
  12. 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
  13. 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
  14. socket_import_stream — Import a stream
  15. socket_last_error — Returns the last error on the socket
  16. socket_listen — Listens for a connection on a socket
  17. socket_read — Reads a maximum of length bytes from a socket
  18. socket_recv — 从已连接的socket接收数据
  19. socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
  20. socket_recvmsg — Read a message
  21. socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
  22. socket_send — Sends data to a connected socket
  23. socket_sendmsg — Send a message
  24. socket_sendto — Sends a message to a socket, whether it is connected or not
  25. socket_set_block — Sets blocking mode on a socket resource
  26. socket_set_nonblock — Sets nonblocking mode for file descriptor fd
  27. socket_set_option — Sets socket options for the socket
  28. socket_setopt — 别名 socket_set_option
  29. socket_shutdown — Shuts down a socket for receiving, sending, or both
  30. socket_strerror — Return a string describing a socket error
  31. socket_write — Write to a socket

更多细节请查看PHP关于socket的官方手册:http://php.net/manual/zh/book.sockets.php

 

一个简单的TCP服务器示例 phptcpserver.php :

 

  1. <?php
  2.  
  3. $servsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个socket
  4.  
  5. if (FALSE === $servsock)
  6. {
  7. $errcode = socket_last_error();
  8. fwrite(STDERR, "socket create fail: " . socket_strerror($errcode));
  9. exit(-1);
  10. }
  11.  
  12. if (!socket_bind($servsock, '127.0.0.1', 8888)) // 绑定ip地址及端口
  13. {
  14. $errcode = socket_last_error();
  15. fwrite(STDERR, "socket bind fail: " . socket_strerror($errcode));
  16. exit(-1);
  17. }
  18.  
  19. if (!socket_listen($servsock, 128)) // 允许多少个客户端来排队连接
  20. {
  21. $errcode = socket_last_error();
  22. fwrite(STDERR, "socket listen fail: " . socket_strerror($errcode));
  23. exit(-1);
  24. }
  25.  
  26. while (1)
  27. {
  28. $connsock = socket_accept($servsock); //响应客户端连接
  29.  
  30. if ($connsock)
  31. {
  32. socket_getpeername($connsock, $addr, $port); //获取连接过来的客户端ip地址和端口
  33. echo "client connect server: ip = $addr, port = $port" . PHP_EOL;
  34.  
  35. while (1)
  36. {
  37. $data = socket_read($connsock, 1024); //从客户端读取数据
  38.  
  39. if ($data === '')
  40. {
  41. //客户端关闭
  42. socket_close($connsock);
  43. echo "client close" . PHP_EOL;
  44. break;
  45. }
  46. else
  47. {
  48. echo 'read from client:' . $data;
  49. $data = strtoupper($data); //小写转大写
  50. socket_write($connsock, $data); //回写给客户端
  51. }
  52. }
  53. }
  54. }
  55.  
  56. 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 代码:

 

  1. <?php
  2.  
  3. $servsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个socket
  4.  
  5. if (FALSE === $servsock)
  6. {
  7. $errcode = socket_last_error();
  8. fwrite(STDERR, "socket create fail: " . socket_strerror($errcode));
  9. exit(-1);
  10. }
  11.  
  12. if (!socket_bind($servsock, '127.0.0.1', 8888)) // 绑定ip地址及端口
  13. {
  14. $errcode = socket_last_error();
  15. fwrite(STDERR, "socket bind fail: " . socket_strerror($errcode));
  16. exit(-1);
  17. }
  18.  
  19. if (!socket_listen($servsock, 128)) // 允许多少个客户端来排队连接
  20. {
  21. $errcode = socket_last_error();
  22. fwrite(STDERR, "socket listen fail: " . socket_strerror($errcode));
  23. exit(-1);
  24. }
  25.  
  26. /* 要监听的三个sockets数组 */
  27. $read_socks = array();
  28. $write_socks = array();
  29. $except_socks = NULL; // 注意 php 不支持直接将NULL作为引用传参,所以这里定义一个变量
  30.  
  31. $read_socks[] = $servsock;
  32.  
  33. while (1)
  34. {
  35. /* 这两个数组会被改变,所以用两个临时变量 */
  36. $tmp_reads = $read_socks;
  37. $tmp_writes = $write_socks;
  38.  
  39. // int socket_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )
  40. $count = socket_select($tmp_reads, $tmp_writes, $except_socks, NULL); // timeout 传 NULL 会一直阻塞直到有结果返回
  41.  
  42. foreach ($tmp_reads as $read)
  43. {
  44.  
  45. if ($read == $servsock)
  46. {
  47. /* 有新的客户端连接请求 */
  48. $connsock = socket_accept($servsock); //响应客户端连接, 此时不会造成阻塞
  49. if ($connsock)
  50. {
  51. socket_getpeername($connsock, $addr, $port); //获取远程客户端ip地址和端口
  52. echo "client connect server: ip = $addr, port = $port" . PHP_EOL;
  53.  
  54. // 把新的连接sokcet加入监听
  55. $read_socks[] = $connsock;
  56. $write_socks[] = $connsock;
  57. }
  58. }
  59. else
  60. {
  61. /* 客户端传输数据 */
  62. $data = socket_read($read, 1024); //从客户端读取数据, 此时一定会读到数组而不会产生阻塞
  63.  
  64. if ($data === '')
  65. {
  66. //移除对该 socket 监听
  67. foreach ($read_socks as $key => $val)
  68. {
  69. if ($val == $read) unset($read_socks[$key]);
  70. }
  71.  
  72. foreach ($write_socks as $key => $val)
  73. {
  74. if ($val == $read) unset($write_socks[$key]);
  75. }
  76.  
  77.  
  78. socket_close($read);
  79. echo "client close" . PHP_EOL;
  80.  
  81. }
  82. else
  83. {
  84. socket_getpeername($read, $addr, $port); //获取远程客户端ip地址和端口
  85.  
  86. echo "read from client # $addr:$port # " . $data;
  87.  
  88. $data = strtoupper($data); //小写转大写
  89.  
  90. if (in_array($read, $tmp_writes))
  91. {
  92. //如果该客户端可写 把数据回写给客户端
  93. socket_write($read, $data);
  94. }
  95. }
  96. }
  97. }
  98. }
  99.  
  100. 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服务器:

 

  1. ....
  2.  
  3. socket_getpeername($read, $addr, $port); //获取远程客户端ip地址和端口
  4.  
  5. echo "read from client # $addr:$port # " . $data;
  6.  
  7. $response = "HTTP/1.1 200 OK\r\n";
  8. $response .= "Server: phphttpserver\r\n";
  9. $response .= "Content-Type: text/html\r\n";
  10. $response .= "Content-Length: 3\r\n\r\n";
  11. $response .= "ok\n";
  12.  
  13. if (in_array($read, $tmp_writes))
  14. {
  15. //如果该客户端可写 把数据回写给客户端
  16. socket_write($read, $response);
  17. socket_close($read); // 主动关闭客户端连接
  18. //移除对该 socket 监听
  19. foreach ($read_socks as $key => $val)
  20. {
  21. if ($val == $read) unset($read_socks[$key]);
  22. }
  23.  
  24. foreach ($write_socks as $key => $val)
  25. {
  26. if ($val == $read) unset($write_socks[$key]);
  27. }
  28. }
  29. .....




重新启动该服务器,用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,有没有小激动呢^^。

posted on 2020-08-27 09:29  爱漂泊人生  阅读(319)  评论(0编辑  收藏  举报

导航