Loading

php socket编程入门

新建PHP文件socket_server.php

<?php

// 判断我们的PHP有没有加载sockets模块
if (!extension_loaded('sockets')) {
    die('对不起你还没有安装sockets扩展.');
}


// 接受客户端请求,回复固定的响应内容
function server_listen_socket ($address, $port)
{
  $buffer = "这个消息来自于服务器,socket say hello";
  $len = strlen($buffer);

  // create, bind and listen to socket

  // 创建通讯节点(套接字)
  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if (! $socket) {
    echo "failed to create socket:" . socket_strerror($socket) . "\n";
    exit();
  }

  // 为这个套接字绑定地址和侦听端口
  $bind_flag = socket_bind($socket, $address, $port);
  if (! $bind_flag) {
    echo "failed to bind socket:" . socket_strerror($bind_flag) . "\n";
    exit();
  }

  // 侦听端口号
  $backlog = 20;
  $listen_flag = socket_listen($socket, $backlog);
  if (! $listen_flag) {
    echo "failed to listen to socket:" . socket_strerror($listen_flag) . "\n";
    exit();
  }

  echo "等待客户端连接中。。。\n";

  while (1) {
    if (($accept_socket = socket_accept($socket)) == FALSE) {
      continue;
    } else {
      socket_write($accept_socket, $buffer, $len);
      socket_close($accept_socket);
    }
  }
}

function run_server ()
{
  // pcntl_fork()返回值如果为-1,则说明执行失败
  // 0说明在子进程中,大于0说明在父进程中
  $pid1 = pcntl_fork();
  if ($pid1 == 0) {
    // first child process

    // 守护进程的一般流程:fork()->setsid()->fork()
    posix_setsid();

    if (($pid2 = pcntl_fork()) == 0) {
      $address = "192.168.3.52";
      $port = "8767";
      server_listen_socket($address, $port);
    } else {
      // 防止获得控制终端
      exit();
    }

  } else {
    // wait for first child process exit
    pcntl_wait($status);
  }
}

// 屏蔽76行,打开79-81行不后台运行,打开76行,关闭79-81行启用后台进程守护

// server守护进程
// run_server();

// 不守护进程
$address = "192.168.3.52";
$port = "8767";
server_listen_socket($address, $port);

客户端用telnet请求

如果打开守护进程,服务器端这样显示

 

posted @ 2016-10-26 14:18  哈利路亚健儿奋起步伐  阅读(152)  评论(0编辑  收藏  举报