如何创建Socket服务(源码)

来源:互联网 发布:windows nextcloud 编辑:程序博客网 时间:2024/06/05 06:50

 <?php
 //端口
 $serverPort = 1234;
 //在指定端口创建socket连接监听(加@可以屏蔽错误)
 $socket = @socket_create_listen($serverPort);
 if(!$socket){
  print "创建socket监听失败!请检查$serverPort端口是否已被占用!/n";
  exit;
 }
 while(true){
  //接收请求
  $client = socket_accept($socket);
  $welcome = "/nWelmome to the My Socket Server./nType'!exit' to close this connection,or type '!die' tohalt whe serer./n";
  //回应给客户端
  socket_write($client,$welcome);
  while(true){
   //读取请求信息
   $input = trim(socket_read($client,256));
   if($input == 'exit'){
    break;
   }
   if($input == 'die'){
    socket_close($client);
    break 2;
   }
   //将字符转为大写
   $output = strtoupper($input)."/n";
   //回应给客户端
   socket_write($client,$output);
   echo $input."/n";
  }
  socket_close($client);
 }
 socket_close($socket);

//完