当前位置:Gxlcms > PHP教程 > phpsocket基础原理|服务端server.php|客户端client.php

phpsocket基础原理|服务端server.php|客户端client.php

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

php socket基础原理,基础使用方法:
服务端:创建一个socket套接字 =》绑定这个socket到指定的IP与端口上 =》监听这个socket的所有链接请求 =》响应或者返回数据
客户端:创建一个socket套接字 =》连接需要请求的socket =》发送数据到socket =》读取socket的响应数据

(~_~)理解不当之处还请同学修正~~~
  1. Server.php
  2. $host = '192.168.0.10';
  3. $port = 88888;
  4. if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
  5. echo "socket create success.\n";
  6. }
  7. if($bind = socket_bind($socket, $host, $port)){
  8. echo "socket bind success.\n";
  9. }
  10. if($listen = socket_listen($socket)){
  11. echo "socket listening...\n";
  12. }
  13. if($connect = socket_accept($socket)){
  14. echo "socket accept a connect success.\n";
  15. }
  16. //===================================================//
  17. socket_write($connect, 'I am from Server.php at DateTime:'.date('Y-m-d H:i:s')."\n");
  18. //====================发送到客户端==================================================//
  19. //==================================================//
  20. $read = socket_read($connect, 1024);
  21. echo $read;
  22. //============接受客户端过来的消息============================//
  23. //while($connect= socket_accept($socket)){
  24. // $read = socket_read($connect, 1024);
  25. // echo $read;
  26. //}
  27. //循环accept
  1. Client.php
  2. $host = '192.168.0.10';
  3. $port = 88888;
  4. if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
  5. echo "socket create success.\n";
  6. }
  7. socket_connect($socket, $host, $port);
  8. //=======================================================//
  9. socket_write($socket, 'I am from client.php at DateTime:'.date('Y-m-d H:i:s')."\n");
  10. //==================向服务端发送请求================================================//
  11. //=======================================================//
  12. $read = socket_read($socket, 1024);
  13. echo $read;
  14. //===============接受服务端的返回数据========================//

人气教程排行