secret
Created

PHP Threading

  • Download Gist
My Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
// Stripped out everything not Thread related
 
 
#!/php -q
<?php
 
include('Thread.php');
 
 
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
 
#$master = WebSocket("localhost",81);
$master = WebSocket("85.25.146.135",12345);
$sockets = array($master);
$users = array();
$debug = true;
$threads = array();
 
 
 
function handleClient($user) {
if (!$user->ircSocket) {
send($user->socket, '###NOPE');
return;
}
send($user->socket, '###YUP');
while (!feof($user->ircSocket)){
$ircInput = fgets($user->ircSocket, 1024);
send($user->socket, $ircInput);
}
}
 
 
while(true){
if(count($threads)> 0){
foreach( $threads as $index => $thread ) {
if( ! $thread->isAlive() ) {
unset( $threads[$index] );
}
}
}
$changed = $sockets;
socket_select($changed,$write=NULL,$except=NULL,NULL);
foreach($changed as $socket){
if($socket==$master){
$client=socket_accept($master);
if($client<0){ console("socket_accept() failed"); continue; }
else{
connect($client);
}
}
else{
$bytes = @socket_recv($socket,$buffer,2048,0);
if($bytes==0){ disconnect($socket); }
else{
$user = getuserbysocket($socket);
if(!$user->handshake){ dohandshake($user,$buffer); }
else{ process($user,$buffer); }
}
}
}
}
 
//---------------------------------------------------------------
function process(&$user,$msg){
global $threads;
$action = unwrap($msg);
say("< ".$action);
if(strpos($action,"QUIT") === 0) {
disconnect($user->socket);
}
if ($action==="###IRC" && $user->ircSocket === null){
$user->ircSocket = fsockopen('irc.freenode.net', 6667, $errno, $errstr, 30);
$t = new Thread('handleClient');
$t->start($user);
array_push($threads, $t);
}
 
if($user->ircSocket){
fwrite($user->ircSocket, $action."\r\n");
}
 
}
 
}
Starter Script
1 2 3 4 5 6 7
<?php
$command ="/usr/bin/php -f /var/www/vhosts/crushhour.net/httpdocs/IRC5/tServer.php > irc5.log &";
exec($command, $arrOutput);
?>
 
 
//usage: php starter.php
Thread Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 
<?php
/**
* Implements threading in PHP
*
* @package <none>
* @version 1.0.0 - stable
* @author Tudor Barbu <miau@motane.lu>
* @copyright MIT
*/
class Thread {
const FUNCTION_NOT_CALLABLE = 10;
const COULD_NOT_FORK = 15;
/**
* possible errors
*
* @var array
*/
private $errors = array(
Thread::FUNCTION_NOT_CALLABLE => 'You must specify a valid function name that can be called from the current scope.',
Thread::COULD_NOT_FORK => 'pcntl_fork() returned a status of -1. No new process was created',
);
/**
* callback for the function that should
* run as a separate thread
*
* @var callback
*/
protected $runnable;
/**
* holds the current process id
*
* @var integer
*/
private $pid;
/**
* checks if threading is supported by the current
* PHP configuration
*
* @return boolean
*/
public static function available() {
$required_functions = array(
'pcntl_fork',
);
foreach( $required_functions as $function ) {
if ( !function_exists( $function ) ) {
return false;
}
}
return true;
}
/**
* class constructor - you can pass
* the callback function as an argument
*
* @param callback $_runnable
*/
public function __construct( $_runnable = null ) {
if( $_runnable !== null ) {
$this->setRunnable( $_runnable );
}
}
/**
* sets the callback
*
* @param callback $_runnable
* @return callback
*/
public function setRunnable( $_runnable ) {
if( self::runnableOk( $_runnable ) ) {
$this->runnable = $_runnable;
}
else {
throw new Exception( $this->getError( Thread::FUNCTION_NOT_CALLABLE ), Thread::FUNCTION_NOT_CALLABLE );
}
}
/**
* gets the callback
*
* @return callback
*/
public function getRunnable() {
return $this->runnable;
}
/**
* checks if the callback is ok (the function/method
* actually exists and is runnable from the current
* context)
*
* can be called statically
*
* @param callback $_runnable
* @return boolean
*/
public static function runnableOk( $_runnable ) {
return ( function_exists( $_runnable ) && is_callable( $_runnable ) );
}
/**
* returns the process id (pid) of the simulated thread
*
* @return int
*/
public function getPid() {
return $this->pid;
}
/**
* checks if the child thread is alive
*
* @return boolean
*/
public function isAlive() {
$pid = pcntl_waitpid( $this->pid, $status, WNOHANG );
return ( $pid === 0 );
}
/**
* starts the thread, all the parameters are
* passed to the callback function
*
* @return void
*/
public function start() {
$pid = @ pcntl_fork();
if( $pid == -1 ) {
throw new Exception( $this->getError( Thread::COULD_NOT_FORK ), Thread::COULD_NOT_FORK );
}
if( $pid ) {
// parent
$this->pid = $pid;
}
else {
// child
pcntl_signal( SIGTERM, array( $this, 'signalHandler' ) );
$arguments = func_get_args();
if ( !empty( $arguments ) ) {
call_user_func_array( $this->runnable, $arguments );
}
else {
call_user_func( $this->runnable );
}
exit( 0 );
}
}
/**
* attempts to stop the thread
* returns true on success and false otherwise
*
* @param integer $_signal - SIGKILL/SIGTERM
* @param boolean $_wait
*/
public function stop( $_signal = SIGKILL, $_wait = false ) {
if( $this->isAlive() ) {
posix_kill( $this->pid, $_signal );
if( $_wait ) {
pcntl_waitpid( $this->pid, $status = 0 );
}
}
}
/**
* alias of stop();
*
* @return boolean
*/
public function kill( $_signal = SIGKILL, $_wait = false ) {
return $this->stop( $_signal, $_wait );
}
/**
* gets the error's message based on
* its id
*
* @param integer $_code
* @return string
*/
public function getError( $_code ) {
if ( isset( $this->errors[$_code] ) ) {
return $this->errors[$_code];
}
else {
return 'No such error code ' . $_code . '! Quit inventing errors!!!';
}
}
/**
* signal handler
*
* @param integer $_signal
*/
protected function signalHandler( $_signal ) {
switch( $_signal ) {
case SIGTERM:
exit( 0 );
break;
}
}
}
 
// EOF

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.