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

php中socket编程一例

程序员文章站 2022-06-03 09:54:41
...
  1. error_reporting(E_ALL);
  2. set_time_limit(0);
  3. echo "

    TCP/IP Connection

    \n";
  4. $port = 1935;
  5. $ip = "127.0.0.1";
  6. /*
  7. +-------------------------------
  8. * @socket连接整个过程
  9. +-------------------------------
  10. * @socket_create
  11. * @socket_connect
  12. * @socket_write
  13. * @socket_read
  14. * @socket_close
  15. +--------------------------------
  16. */
  17. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  18. if ($socket echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
  19. }else {
  20. echo "OK.\n";
  21. }
  22. echo "试图连接 '$ip' 端口 '$port'...\n";
  23. $result = socket_connect($socket, $ip, $port);
  24. if ($result echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
  25. }else {
  26. echo "连接OK\n";
  27. }
  28. $in = "Ho\r\n";
  29. $in .= "first blood\r\n";
  30. $out = '';
  31. if(!socket_write($socket, $in, strlen($in))) {
  32. echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
  33. }else {
  34. echo "发送到服务器信息成功!\n";
  35. echo "发送的内容为:$in
    ";
  36. }
  37. while($out = socket_read($socket, 8192)) {
  38. echo "接收服务器回传信息成功!\n";
  39. echo "接受的内容为:",$out;
  40. }
  41. echo "关闭SOCKET...\n";
  42. socket_close($socket);
  43. echo "关闭OK\n";
  44. ?>
复制代码

服务器端代码:

  1. //确保在连接客户端时不会超时
  2. set_time_limit(0);
  3. $ip = '127.0.0.1';
  4. $port = 1935;
  5. /*
  6. +-------------------------------
  7. * @socket通信整个过程
  8. +-------------------------------
  9. * @socket_create
  10. * @socket_bind
  11. * @socket_listen
  12. * @socket_accept
  13. * @socket_read
  14. * @socket_write
  15. * @socket_close
  16. +--------------------------------
  17. */
  18. /*----------------以下操作都是手册上的-------------------*/
  19. if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n";
  20. }
  21. if(($ret = socket_bind($sock,$ip,$port)) echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";
  22. }
  23. if(($ret = socket_listen($sock,4)) echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";
  24. }
  25. $count = 0;
  26. do {
  27. if (($msgsock = socket_accept($sock)) echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
  28. echo "等待连接...";
  29. break;
  30. } else {
  31. //发到客户端
  32. $msg ="测试成功!\n";
  33. socket_write($msgsock, $msg, strlen($msg));
  34. echo "测试成功了啊\n";
  35. $buf = socket_read($msgsock,8192);
  36. $talkback = "收到的信息:$buf\n";
  37. echo $talkback;
  38. if(++$count >= 5){
  39. break;
  40. };
  41. }
  42. //echo $buf;
  43. socket_close($msgsock);
  44. } while (true);
  45. socket_close($sock);
  46. ?>
复制代码