php socket实现的聊天室代码分享


Posted in PHP onAugust 16, 2014
/**
* patServer
* PHP socket server base class
* Events that can be handled:
*  * onStart
*  * onConnect
*  * onConnectionRefused
*  * onClose
*  * onShutdown
*  * onReceiveData
*
* @version 1.1
* @author  Stephan Schmidt <schst@php-tools.de>
* @package patServer
*/
class patServer {
/**
* information about the project
* @var array $systemVars
*/
var $systemVars  = array(
  "appName"  => "patServer",
  "appVersion"  => "1.1",
  "author"  => array("Stephan Schmidt <schst@php-tools.de>", )
  );

/**
* port to listen
* @var integer  $port
*/
  var $port  = 10000;

/**
* domain to bind to
* @var string $domain
*/
  var $domain  = "localhost";

/**
* maximum amount of clients
* @var integer $maxClients
*/
  var $maxClients = -1;

/**
* buffer size for socket_read
* @var integer $readBufferSize
*/
  var $readBufferSize  = 128;

/**
* end character for socket_read
* @var integer $readEndCharacter
*/
  var $readEndCharacter = "\n";

/**
* maximum of backlog in queue
* @var integer $maxQueue
*/
  var $maxQueue = 500;

/**
* debug mode
* @var boolean $debug
*/
  var $debug  = true;

/**
* debug mode
* @var string $debugMode
*/
  var $debugMode = "text";

/**
* debug destination (filename or stdout)
* @var string $debugDest
*/
  var $debugDest = "stdout";

/**
* empty array, used for socket_select
* @var array $null
*/
  var $null  = array();

/**
* all file descriptors are stored here
* @var array $clientFD
*/
  var $clientFD = array();

/**
* needed to store client information
* @var array $clientInfo
*/
  var $clientInfo = array();

/**
* needed to store server information
* @var array $serverInfo
*/
  var $serverInfo = array();

/**
* amount of clients
* @var integer  $clients
*/
  var $clients = 0;

/**
* create a new socket server
*
* @access public
* @param string  $domain  domain to bind to
* @param integer  $port  port to listen to
*/
function patServer( $domain = "localhost", $port = 10000 )
{
  $this->domain = $domain;
  $this->port  = $port;

  $this->serverInfo["domain"]     = $domain;
  $this->serverInfo["port"]     = $port;
  $this->serverInfo["servername"]   = $this->systemVars["appName"];
  $this->serverInfo["serverversion"] = $this->systemVars["appVersion"];

  set_time_limit( 0 );
}

/**
* set maximum amount of simultaneous connections
*
* @access public
* @param int $maxClients
*/
function setMaxClients( $maxClients )
{
  $this->maxClients = $maxClients;
}

/**
* set debug mode
*
* @access public
* @param mixed $debug [text|htmlfalse]
* @param string $dest destination of debug message (stdout to output or filename if log should be written)
*/
function setDebugMode( $debug, $dest = "stdout" )
{
  if( $debug === false )
  {
  $this->debug = false;
  return true;
  }

  $this->debug  = true;
  $this->debugMode = $debug;
  $this->debugDest = $dest;
}

/**
* start the server
*
* @access public
* @param int $maxClients
*/
function start()
{
  $this->initFD = @socket_create( AF_INET, SOCK_STREAM, 0 );
  if( !$this->initFD )
  die( "patServer: Could not create socket." );

  // adress may be reused
  socket_setopt( $this->initFD, SOL_SOCKET, SO_REUSEADDR, 1 );

  // bind the socket
  if( !@socket_bind( $this->initFD, $this->domain, $this->port ) )
  {
  @socket_close( $this->initFD );
  die( "patServer: Could not bind socket to ".$this->domain." on port ".$this->port." ( ".$this->getLastSocketError( $this->initFd )." )." );
  }

  // listen on selected port
  if( !@socket_listen( $this->initFD, $this->maxQueue ) )
  die( "patServer: Could not listen ( ".$this->getLastSocketError( $this->initFd )." )." );

  $this->sendDebugMessage( "Listening on port ".$this->port.". Server started at ".date( "H:i:s", time() ) );

  // this allows the shutdown function to check whether the server is already shut down
  $GLOBALS["_patServerStatus"] = "running";
  // this ensures that the server will be sutdown correctly
  register_shutdown_function( array( $this, "shutdown" ) );

  if( method_exists( $this, "onStart" ) )
  $this->onStart();

  $this->serverInfo["started"] = time();
  $this->serverInfo["status"]  = "running";

  while( true )
  {
  $readFDs = array();
  array_push( $readFDs, $this->initFD );

  // fetch all clients that are awaiting connections
  for( $i = 0; $i < count( $this->clientFD ); $i++ )
   if( isset( $this->clientFD[$i] ) )
   array_push( $readFDs, $this->clientFD[$i] );

  // block and wait for data or new connection
  $ready = @socket_select( $readFDs, $this->null, $this->null, NULL );

  if( $ready === false )
  {
   $this->sendDebugMessage( "socket_select failed." );
   $this->shutdown();
  }

  // check for new connection
  if( in_array( $this->initFD, $readFDs ) )
  {
   $newClient = $this->acceptConnection( $this->initFD );

   // check for maximum amount of connections
   if( $this->maxClients > 0 )
   {
   if( $this->clients > $this->maxClients )
   {
    $this->sendDebugMessage( "Too many connections." );

    if( method_exists( $this, "onConnectionRefused" ) )
    $this->onConnectionRefused( $newClient );

    $this->closeConnection( $newClient );
   }
   }

   if( --$ready <= 0 )
   continue;
  }

  // check all clients for incoming data
  for( $i = 0; $i < count( $this->clientFD ); $i++ )
  {
   if( !isset( $this->clientFD[$i] ) )
   continue;

   if( in_array( $this->clientFD[$i], $readFDs ) )
   {
   $data = $this->readFromSocket( $i );

   // empty data => connection was closed
   if( !$data )
   {
    $this->sendDebugMessage( "Connection closed by peer" );
    $this->closeConnection( $i );
   }
   else
   {
    $this->sendDebugMessage( "Received ".trim( $data )." from ".$i );

    if( method_exists( $this, "onReceiveData" ) )
    $this->onReceiveData( $i, $data );
   }
   }
  }
  }
}

/**
* read from a socket
*
* @access private
* @param integer $clientId internal id of the client to read from
* @return string $data  data that was read
*/
function readFromSocket( $clientId )
{
  // start with empty string
  $data  = "";

  // read data from socket
  while( $buf = socket_read( $this->clientFD[$clientId], $this->readBufferSize ) )
  {
  $data .= $buf;

  $endString = substr( $buf, - strlen( $this->readEndCharacter ) );
  if( $endString == $this->readEndCharacter )
   break;
  if( $buf == NULL )
   break;
  }

  if( $buf === false )
  $this->sendDebugMessage( "Could not read from client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." );

  return $data;
}

/**
* accept a new connection
*
* @access public
* @param resource &$socket socket that received the new connection
* @return int  $clientID internal ID of the client
*/
function acceptConnection( &$socket )
{
  for( $i = 0 ; $i <= count( $this->clientFD ); $i++ )
  {
  if( !isset( $this->clientFD[$i] ) || $this->clientFD[$i] == NULL )
  {
   $this->clientFD[$i] = socket_accept( $socket );
   socket_setopt( $this->clientFD[$i], SOL_SOCKET, SO_REUSEADDR, 1 );
   $peer_host = "";
   $peer_port = "";
   socket_getpeername( $this->clientFD[$i], $peer_host, $peer_port );
   $this->clientInfo[$i] = array(
       "host"  => $peer_host,
       "port"  => $peer_port,
       "connectOn" => time()
       );
   $this->clients++;

   $this->sendDebugMessage( "New connection ( ".$i." ) from ".$peer_host." on port ".$peer_port );

   if( method_exists( $this, "onConnect" ) )
   $this->onConnect( $i );
   return $i;
  }
  }
}

/**
* check, whether a client is still connected
*
* @access public
* @param integer $id client id
* @return boolean $connected true if client is connected, false otherwise
*/
function isConnected( $id )
{
  if( !isset( $this->clientFD[$id] ) )
  return false;
  return true;
}

/**
* close connection to a client
*
* @access public
* @param int $clientID internal ID of the client
*/
function closeConnection( $id )
{
  if( !isset( $this->clientFD[$id] ) )
  return false;

  if( method_exists( $this, "onClose" ) )
  $this->onClose( $id );

  $this->sendDebugMessage( "Closed connection ( ".$id." ) from ".$this->clientInfo[$id]["host"]." on port ".$this->clientInfo[$id]["port"] );

  @socket_close( $this->clientFD[$id] );
  $this->clientFD[$id] = NULL;
  unset( $this->clientInfo[$id] );
  $this->clients--;
}

/**
* shutdown server
*
* @access public
*/
function shutDown()
{
  if( $GLOBALS["_patServerStatus"] != "running" )
  exit;
  $GLOBALS["_patServerStatus"] = "stopped";

  if( method_exists( $this, "onShutdown" ) )
  $this->onShutdown();

  $maxFD = count( $this->clientFD );
  for( $i = 0; $i < $maxFD; $i++ )
  $this->closeConnection( $i );

  @socket_close( $this->initFD );

  $this->sendDebugMessage( "Shutdown server." );
  exit;
}

/**
* get current amount of clients
*
* @access public
* @return int $clients amount of clients
*/
function getClients()
{
  return $this->clients;
}

/**
* send data to a client
*
* @access public
* @param int  $clientId ID of the client
* @param string $data  data to send
* @param boolean $debugData flag to indicate whether data that is written to socket should also be sent as debug message
*/
function sendData( $clientId, $data, $debugData = true )
{
  if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL )
  return false;

  if( $debugData )
  $this->sendDebugMessage( "sending: \"" . $data . "\" to: $clientId" );

  if( !@socket_write( $this->clientFD[$clientId], $data ) )
  $this->sendDebugMessage( "Could not write '".$data."' client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." );
}

/**
* send data to all clients
*
* @access public
* @param string $data  data to send
* @param array $exclude client ids to exclude
*/
function broadcastData( $data, $exclude = array(), $debugData = true )
{
  if( !empty( $exclude ) && !is_array( $exclude ) )
  $exclude = array( $exclude );

  for( $i = 0; $i < count( $this->clientFD ); $i++ )
  {
  if( isset( $this->clientFD[$i] ) && $this->clientFD[$i] != NULL && !in_array( $i, $exclude ) )
  {
   if( $debugData )
   $this->sendDebugMessage( "sending: \"" . $data . "\" to: $i" );

   if( !@socket_write( $this->clientFD[$i], $data ) )
   $this->sendDebugMessage( "Could not write '".$data."' client ".$i." ( ".$this->getLastSocketError( $this->clientFD[$i] )." )." );
  }
  }
}

/**
* get current information about a client
*
* @access public
* @param int  $clientId ID of the client
* @return array $info  information about the client
*/
function getClientInfo( $clientId )
{
  if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL )
  return false;
  return $this->clientInfo[$clientId];
}

/**
* send a debug message
*
* @access private
* @param string $msg message to debug
*/
function sendDebugMessage( $msg )
{
  if( !$this->debug )
  return false;

  $msg = date( "Y-m-d H:i:s", time() ) . " " . $msg;

  switch( $this->debugMode )
  {
  case "text":
   $msg = $msg."\n";
   break;
  case "html":
   $msg = htmlspecialchars( $msg ) . "<br />\n";
   break;
  }

  if( $this->debugDest == "stdout" || empty( $this->debugDest ) )
  {
  echo $msg;
  flush();
  return true;
  }

  error_log( $msg, 3, $this->debugDest );
  return true;
}

/**
* return string for last socket error
*
* @access public
* @return string $error last error
*/
function getLastSocketError( &$fd )
{
  $lastError = socket_last_error( $fd );
  return "msg: " . socket_strerror( $lastError ) . " / Code: ".$lastError;
}
function onReceiveData($ip,$data){

  $this->broadcastData( $data,array(), true );
}
}


$patServer = new patServer();
$patServer->start();
PHP 相关文章推荐
小偷PHP+Html+缓存
Dec 20 PHP
PHP源代码数组统计count分析
Aug 02 PHP
php程序的国际化实现方法(利用gettext)
Aug 14 PHP
php 注释规范
Mar 29 PHP
基于initPHP的框架介绍
Apr 18 PHP
php使用pdo连接mssql server数据库实例
Dec 25 PHP
php的crc32函数使用时需要注意的问题(不然就是坑)
Apr 21 PHP
PHP使用自定义方法实现数组合并示例
Jul 07 PHP
Yii2实现上下联动下拉框功能的方法
Aug 10 PHP
php模仿qq空间或朋友圈发布动态、评论动态、回复评论、删除动态或评论的功能(中)
Jun 11 PHP
PHP编程文件处理类SplFileObject和SplFileInfo用法实例分析
Jul 22 PHP
laravel执行php artisan migrate报错的解决方法
Oct 09 PHP
php与flash as3 socket通信传送文件实现代码
Aug 16 #PHP
php操作XML、读取数据和写入数据的实现代码
Aug 15 #PHP
php中操作memcached缓存进行增删改查数据的实现代码
Aug 15 #PHP
php上传图片之时间戳命名(保存路径)
Aug 15 #PHP
php中将一段数据存到一个txt文件中并显示其内容
Aug 15 #PHP
PHP反向代理类代码
Aug 15 #PHP
ThinkPHP中自定义目录结构的设置方法
Aug 15 #PHP
You might like
Smarty安装配置方法
2008/04/10 PHP
Windows Apache2.2.11及Php5.2.9-1的安装与配置方法
2009/06/08 PHP
PHP循环结构实例讲解
2014/02/10 PHP
使用swoole扩展php websocket示例
2014/02/13 PHP
ThinkPHP3.1新特性之内容解析输出详解
2014/06/19 PHP
PHP反射API示例分享
2016/10/08 PHP
laravel框架使用极光推送消息操作示例
2020/02/15 PHP
用JavaScript 处理 URL 的两个函数代码
2007/08/13 Javascript
js获取元素到文档区域document的(横向、纵向)坐标的两种方法
2013/05/17 Javascript
JavaScript数组前面插入元素的方法
2015/04/06 Javascript
apply和call方法定义及apply和call方法的区别
2015/11/15 Javascript
果断收藏9个Javascript代码高亮脚本
2016/01/06 Javascript
JS简单设置下拉选择框默认值的方法
2016/08/20 Javascript
3种不同的ContextMenu右键菜单实现代码
2016/11/03 Javascript
浅谈js键盘事件全面控制
2016/12/01 Javascript
关于axios返回空对象的问题解决
2017/04/04 Javascript
javaScript手机号码校验工具类PhoneUtils详解
2017/12/08 Javascript
JavaScript实现微信红包算法及问题解决方法
2018/04/26 Javascript
Vue框架下引入ActiveX控件的问题解决
2019/03/25 Javascript
javascript自定义日期比较函数用法示例
2019/07/22 Javascript
node.js使用mongoose操作数据库实现购物车的增、删、改、查功能示例
2019/12/23 Javascript
linux服务器快速卸载安装node环境(简单上手)
2021/02/22 Javascript
利用 Monkey 命令操作屏幕快速滑动
2016/12/07 Python
python同时遍历数组的索引和值的实例
2018/11/15 Python
python判断单向链表是否包括环,若包含则计算环入口的节点实例分析
2019/10/23 Python
python openCV实现摄像头获取人脸图片
2020/08/20 Python
欧洲第一的摇滚和金属乐队服装网站:EMP
2017/10/26 全球购物
Lookfantastic希腊官网:英国知名美妆购物网站
2018/09/15 全球购物
美国在线眼镜店:GlassesShop
2018/11/15 全球购物
二年级体育教学反思
2014/01/15 职场文书
创业女性典型材料
2014/05/02 职场文书
优秀工会工作者事迹材料
2014/06/02 职场文书
环卫工人节活动总结
2014/08/29 职场文书
纺织工程专业推荐信
2014/09/08 职场文书
书法社团活动总结
2015/05/07 职场文书
教你如何使用Python Tkinter库制作记事本
2021/06/10 Python