PHP实现Socket服务器

本文展示了一个使用 PHP 的 Socket 编程实现的简单服务器端示例,该服务器能够监听指定 IP 地址及端口上的连接请求,并与客户端进行交互。通过此示例可以了解如何创建 Socket、绑定地址、监听连接以及读写数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
ob_implicit_flush();
set_time_limit(0);

$address = "192.40.7.93";//换成你自己的地址
$port = 10000;

if(($socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) == false)
 echo "错误(socket_create):".socket_strerror(socket_last_error())."<br />";
 
if(socket_bind($socket,$address,$port) == false)
 echo "错误(socket_bind):".socket_strerror(socket_last_error())."<br />";
 
if(socket_listen($socket) == false)
 echo "错误(socket_listen):".socket_strerror(socket_last_error())."<br />";
 
/*
After the socket socket has been created using socket_create() and bound to a name with socket_bind(),
it may be told to listen for incoming connections on socket.
*/

while(true){
 if(($msgSocket = socket_accept($socket)) == false){
  echo "错误(socket_accept):".socket_strerror(socket_last_error())."<br />";
  break;
 }
 
 /*
 this function will accept incoming connections on that socket.
 Once a successful connection is made, a new socket resource is returned, which may be used for communication.
 If there are multiple connections queued on the socket, the first will be used.
 If there are no pending connections, socket_accept() will block until a connection becomes present.
 If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned. 
 */
 
 $msg = "Welcome!<br />";
 //socket_write($msg,$msg,strlen($msg));
 $command = "";
 
 while(true){
  if(($buf = socket_read($msgSocket,2048,PHP_BINARY_READ)) == false){
   echo "错误(socket_read):".socket_strerror(socket_last_error())."<br />";
   break 2;
  }
  
  /*
  The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions.
  The maximum number of bytes read is specified by the length parameter.
  Otherwise you can use /r, /n, or /0 to end reading (depending on the type parameter, see below).   
  */
  
  /*
  if(!$buf = trim($buf))
   continue; // ????
   
  if($buf == "quit")
   break;
  
  if($buf == "shutdown"){
   socket_close($msgSocket);
   break 2;
  }
  
  $tallBack = "You say:$buf/n";
  socket_write($msgSocket,$tallBack,strlen($tallBack));
  */
  
  if(ord($buf) != 13)
   $command .= $buf;
  else{
   $command1 = "You Say:$command/r/n";
   socket_write($msgSocket,$command1,strlen($command1));
   echo "User typed:".$command."<br />";
   $command = "";
  }
 }
 socket_close($msgSocket);
}

socket_close($socket);
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值