zoukankan      html  css  js  c++  java
  • php socket多进程简单服务器(一)

    进程,线程  IO复用,协程都是处理完成并发的方式

    socket分为  三步 服务器监听,客户端请求,连接确认,

    每次连接都由当前进程来处理,可以通过IO复用来解决这个问题,

    这次通过进程来完成并发请求,但是这种方式开销大,消耗较多,频繁的创建和销毁也是耗时

    线程并发  IO复用 等下次在贴代码

    进程并发代码 服务端代码

     1 <?php
     2 $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die("error:".socket_strerror(socket_last_error()));
     3 socket_bind($socket,"192.168.33.1","8000") or die("error:".socket_strerror(socket_last_error()));
     4 socket_set_option($socket, SOL_SOCKET , SO_REUSEADDR , 1);#可以重复使用端口号
     5 socket_listen($socket,5);
     6 while(true){
     7     print("******等待新客户端的到来*******
    ");
     8     $clien = socket_accept($socket) or die("error:".socket_strerror(socket_last_error()));
     9     $pid = pcntl_fork();
    10     #posix_setsid();
    11     if ($pid == -1) {
    12         die('fork failed');
    13     } else if ($pid == 0) {
    14         hanld_seesion($clien);
    15     } else {
    16         #pcntl_wait($status);
    17     }
    18 }
    19 
    20 function hanld_seesion($clien){
    21     socket_getpeername($clien,$ip,$port);
    22     $id = posix_getpid();
    23     print("进程ID:$id == 客户端:".$ip.":".$port."已连接
    ");
    24     while(true){
    25         $data = socket_read($clien,1024);
    26         if(mb_strlen($data) == 0)
    27         {
    28             print("进程ID:$id == 客户端:".$ip.":".$port."断开连接
    ");
    29             socket_close($clien);
    30             exit();
    31         }
    32         print($ip.":".$port.">>:".$data."
    ");
    33     }
    34 }

    客户端代码

    1 <?php
    2 $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die("error:".socket_strerror(socket_last_error()));
    3 $msg = "Ping!";
    4 $len = strlen($msg);
    5 $server = socket_connect($socket,'192.168.33.1', 8000);
    6 socket_write($socket, $msg);
    7 sleep(30);
    8 socket_close($socket);

        

  • 相关阅读:
    HackerRank "Minimum Average Waiting Time" !
    HackerRank "Components in a graph"
    LeetCode "Range Sum Query
    LeetCode "Additive Number"
    LintCode "Post Office Problem" !!!
    LintCode "Longest Increasing Continuous subsequence II" !!
    LintCode "Coins in a Line III" !!
    LeetCode "Range Sum Query 2D
    LeetCode "Smallest Rectangle Enclosing Black Pixels"
    LintCode "Coins in a Line II" !
  • 原文地址:https://www.cnblogs.com/zz-952/p/10481616.html
Copyright © 2011-2022 走看看