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

/**
* 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
, socket
聊天室
websocket实现聊天室、socket实现聊天室、php socket实现聊天室、c socket实现聊天室、websocket聊天室源码,以便于您获取更多的相关知识。

时间: 2024-10-02 10:36:49

php socket实现的聊天室代码分享_php技巧的相关文章

php+html5基于websocket实现聊天室的方法_php技巧

本文实例讲述了php+html5基于websocket实现聊天室的方法.分享给大家供大家参考.具体如下: html5的websocket 实现了双向通信,折腾了几天弄了个聊天室,分享给大家 <?php error_reporting(E_ALL); ob_implicit_flush(); $sk=new Sock('127.0.0.1',8000); $sk->run(); class Sock{ public $sockets; public $users; public $master;

PHP版QQ互联OAuth示例代码分享_php技巧

由于国内QQ用户的普遍性,所以现在各大网站都尽可能的提供QQ登陆口,下面我们来看看php版,给大家参考下 /** * QQ互联 oauth * @author dyllen * */ class Oauth { //取Authorization Code Url const PC_CODE_URL = 'https://graph.qq.com/oauth2.0/authorize'; //取Access Token Url const PC_ACCESS_TOKEN_URL = 'https:

基于GD2图形库的PHP生成图片缩略图类代码分享_php技巧

要使用PHP生成图片缩略图,要保证你的PHP服务器安装了GD2图形库 使用一个类生成图片的缩略图 1.使用方法 $resizeimage = new resizeimage("图片源文件地址", "200", "100", "0","缩略图地址"); //就只用上面的一句话,就能生成缩略图,其中,源文件和缩略图地址可以相同,200,100分别代表宽和高 2. 缩略图类代码 //使用如下类就可以生成图片缩略图

php处理单文件、多文件上传代码分享_php技巧

php处理  单文件.多文件上传实例代码,供大家参考,具体内容如下  后台处理文件submit_form_process.php  <?php /****************************************************************************** 参数说明: $max_file_size : 上传文件大小限制, 单位BYTE $destination_folder : 上传文件路径 $watermark : 是否附加水印(1为加水印,其他为

5种PHP创建数组的实例代码分享_php技巧

看这篇文章之前相信大家都已经看过PHP中文手册关于数组这一节的讲解了,怎么样呢,看懂了多少?至少我第一次阅读文档时是一头雾水,也许是因为在翻译的不够通俗易懂吧^_^!!这里UncleToo根据自己的经验,将数组的各种创建方式用PHP实例代码的方式分享给大家,希望对大家有些帮助(当然,PHP文档还是要多看的) 1.使用array()创建数组 array()创建数组是我们在PHP开发过程中最常用到的一种方式,准确来说array()是一种结构而不是一个函数. 示例1: 复制代码 代码如下: <?php

php实现文件下载代码分享_php技巧

简单的文件下载只需要使用HTML的连接标记<a>,并将属性href的URL值指定为下载的文件即可.所示: <a href="http://www.jb51.net/download/book.rar">下载文件</a> 如果通过上面的代码实现文件下载,只能处理一些浏览器不能默认识别的MIME类型文件,例如当访问book.rar文件时,浏览器并没有直接打开,而是弹出一个下载提示框,提示用户"下载"还是"打开"等处

PHP发送短信代码分享_php技巧

方法一(比较好,推荐) //PHP发送短信 Monxin专用(PHP代码函数) //本代码基于Monxin 运行 //代码来源:Monxin ./config/functions.php function sms($config,$language,$pdo,$sender,$phone_number,$content){ //demo var_dump(sms(self::$config,self::$language,$pdo,"system","18074507509,

php商品对比功能代码分享_php技巧

下面是自己亲自动手编写的代码,和大家一起学习研究. 商品对比调用的JS文件(包含了商品对比框浮动JS): /*浮动窗口*/ (function(){ var n=10; var obj=document.getElementById("goods-compare"); if(!obj){ return false; } var x=0; window.onscroll=function(){ obj.style.top=(document.body.scrollTop||documen

PHP判断浏览器、判断语言代码分享_php技巧

PHP编程中经常需要用到一些服务器的一些资料,特把$_SERVER的详细参数整理下,方便以后使用. 判断浏览器类型 复制代码 代码如下: //判断类型   <?php if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 8.0"))  echo "Internet Explorer 8.0";  else if(strpos($_SERVER["HTTP_USER_AGENT"],&q