zoukankan      html  css  js  c++  java
  • PHP Socket 编程过程详解

    服务端(server.php)

    // set some variables
    $host = "127.0.0.1";
    $port = 25003;
    // don't timeout!
    set_time_limit(0);
    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket
    ");
    // bind socket to port
    $result = socket_bind($socket, $host, $port) or die("Could not bind to socket
    ");
    // start listening for connections
    $result = socket_listen($socket, 3) or die("Could not set up socket listener
    ");
    
    // accept incoming connections
    // spawn another socket to handle communication
    $spawn = socket_accept($socket) or die("Could not accept incoming connection
    ");
    // read client input
    $input = socket_read($spawn, 1024) or die("Could not read input
    ");
    // clean up input string
    $input = trim($input);
    echo "Client Message : ".$input;
    // reverse client input and send back
    $output = strrev($input) . "
    ";
    socket_write($spawn, $output, strlen ($output)) or die("Could not write output
    ");
    // close sockets
    socket_close($spawn);
    socket_close($socket);



    客户端(client.php)

    $host    = "127.0.0.1";
    $port    = 25003;
    $message = "Hello Server";
    echo "Message To server :".$message;
    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket
    ");
    // connect to server
    $result = socket_connect($socket, $host, $port) or die("Could not connect to server
    ");  
    // send string to server
    socket_write($socket, $message, strlen($message)) or die("Could not send data to server
    ");
    // get server response
    $result = socket_read ($socket, 1024) or die("Could not read server response
    ");
    echo "Reply From Server  :".$result;
    // close socket
    socket_close($socket);

    建立上述文件(server.php和client.php)后,执行如下操作:

    1. 复制www目录中的这些文件(假设WAMP),安置于C:wamp。
    2. 打开Web浏览器,在地址栏中键入localhost 。
    3. 先浏览server.php然后client.php。
  • 相关阅读:
    ftp的虚拟用户的使用
    系统进程与线程
    mysql 100%占用的解决
    两张神图介绍python3和 2.x与 3.x 的区别
    python3中__get__,__getattr__,__getattribute__的区别
    Python 数据图表工具的比较
    Spark入门(Python)
    别学框架,学架构
    Python垃圾回收机制
    pyextend库-accepts函数参数检查
  • 原文地址:https://www.cnblogs.com/qiandu/p/5445508.html
Copyright © 2011-2022 走看看