欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP监听Socket

程序员文章站 2022-06-09 15:10:25
...
PHP监听Socket




  1. set_time_limit(10);
  2. $commonProtocol = getprotobyname("tcp");
  3. $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
  4. if ($socket) {
  5. $result = socket_bind($socket, 'localhost', 1337);
  6. if ($result) {
  7. $result = socket_listen($socket, 5);
  8. if ($result) {
  9. echo "监听成功";
  10. }
  11. }
  12. }else{
  13. echo "监听失败";
  14. }
  15. do {
  16. if (($msgsock = socket_accept($socket))) { /* 发送提示信息给连接上来的用户 */
  17. $msg = "==========================================\r\n" .
  18. "Welcome to the PHP Test Server. \r\n\r\n" .
  19. "To quit, type 'quit'. \r\n" .
  20. "To shut down the server type 'shutdown'.\r\n" .
  21. "To get help message type 'help'.\r\n" .
  22. "==========================================\r\n" .
  23. "php>";
  24. }
  25. socket_write($msgsock, $msg, strlen($msg));
  26. do {
  27. $buf = socket_read($msgsock, 2048, PHP_BINARY_READ);
  28. if (false === $buf) {
  29. echo "socket_read() failed: reason: " . socket_strerror($result) . "\n";
  30. break 2;
  31. }
  32. if (!$buf = trim($buf)) {
  33. continue;
  34. } /* 客户端输入quit命令时候关闭客户端连接 */
  35. if ($buf == 'q') {
  36. break;
  37. } /* 客户端输入shutdown命令时候服务端和客户端都关闭 */
  38. if ($buf == 'shutdown') {
  39. socket_close($msgsock);
  40. break 2;
  41. } /* 客户端输入help命令时候输出帮助信息 */
  42. if ($buf == 'h') {
  43. $msg = " PHP Server Help Message \r\n\r\n" .
  44. " To quit, type 'quit'. \r\n" .
  45. " To shut down the server type 'shutdown'.\r\n" .
  46. " To get help message type 'help'.\r\n" .
  47. "php> ";
  48. socket_write($msgsock, $msg, strlen($msg));
  49. continue;
  50. } /* 客户端输入命令不存在时提示信息 */
  51. $talkback = "PHP: unknow command '$buf'.\r\nphp> ";
  52. socket_write($msgsock, $talkback, strlen($talkback));
  53. echo "$buf\n";
  54. } while (true);
  55. socket_close($msgsock);
  56. }while (true);
  57. /* 关闭Socket连接 */
  58. socket_close($socket);
复制代码
相关标签: PHP监听Socket