查看: 576|回复: 0

[PHP实例] 用PHP的socket实现客户端到服务端的通信实例详解

发表于 2017-11-22 08:00:13
句号论坛

一、server.php服务端:

  1. <?php
  2. error_reporting(E_ALL);
  3. set_time_limit(0);
  4. ob_implicit_flush();
  5. //本地IP
  6. $address = 'localhost';
  7. //设置用111端口进行通信
  8. $port = 111;
  9. //创建SOCKET
  10. if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
  11. echo "socket创建失败原因 " . socket_strerror($sock) . "\n";
  12. }
  13. if (($ret = socket_bind($sock, $address, $port)) < 0) {
  14. echo "创建套接字失败原因 " . socket_strerror($ret) . "\n";
  15. }
  16. //监听
  17. if (($ret = socket_listen($sock, 5)) < 0) {
  18. echo "监听失败原因 " . socket_strerror($ret) . "\n";
  19. }
  20. do {
  21. //接收命令
  22. if (($msgsock = @socket_accept($sock)) < 0) {
  23. echo "命令接收失败原因: " . socket_strerror($msgsock) . "\n";
  24. break;
  25. }
  26. $msg = "\nPHP Test Server. \n" ."用quit,shutdown,sun...等命令测试.\n";
  27. @socket_write($msgsock, $msg, strlen($msg));
  28. do {
  29. if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
  30. echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n";
  31. break 2;
  32. }
  33. if (!$buf = trim($buf)) {
  34. continue;
  35. }
  36. if ($buf == 'quit') {
  37. break;
  38. }
  39. if ($buf == 'shutdown') {
  40. socket_close($msgsock);
  41. break 2;
  42. }
  43. if ($buf == 'sun') {
  44. echo'what are you doing?';
  45. }
  46. $talkback = "Backinformation : '$buf'.\n";
  47. socket_write($msgsock, $talkback, strlen($talkback));
  48. echo "$buf\n";
  49. } while (true);
  50. socket_close($msgsock);
  51. } while (true);
  52. socket_close($sock);
  53. ?>
复制代码

二、client.php客户端:

  1. <?php
  2. error_reporting(E_ALL);
  3. //端口111
  4. $service_port = 111;
  5. //本地
  6. $address = 'localhost';
  7. //创建 TCP/IP socket
  8. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  9. if ($socket < 0) {
  10. echo "socket创建失败原因: " . socket_strerror($socket) . "\n";
  11. } else {
  12. echo "OK,HE HE.\n";
  13. }
  14. $result = socket_connect($socket, $address, $service_port);
  15. if ($result < 0) {
  16. echo "SOCKET连接失败原因: ($result) " . socket_strerror($result) . "\n";
  17. } else {
  18. echo "OK.\n";
  19. }
  20. //发送命令
  21. $in = "HEAD / HTTP/1.1\r\n";
  22. $in .= "Connection: Close\r\n\r\n";
  23. $out = '';
  24. echo "Send Command..........";
  25. $in = "sun\n";
  26. socket_write($socket, $in, strlen($in));
  27. echo "OK.\n";
  28. echo "Reading Backinformatin:\n\n";
  29. while ($out = socket_read($socket, 2048)) {
  30. echo $out;
  31. }
  32. echo "Close socket........";
  33. socket_close($socket);
  34. echo "OK,He He.\n\n";
  35. ?>
复制代码

这两段代码是简单介绍用PHP实现客户端和服务端的通信

具体操作,在DOS下用PHP命令打开SERVER,处于监听状态..

再打开一个DOS窗口,用PHP命令打开CLIENT,会得到服务端的回应....

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



太阳http代理AD
回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条