当前位置:Gxlcms > PHP教程 > PHP监听Socket

PHP监听Socket

时间:2021-07-01 10:21:17 帮助过:12人阅读

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);

人气教程排行