Jump to content

[PHP] Socket Server

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Affix

Affix

    Learning Programmer

  • Members
  • PipPipPip
  • 47 posts
<?php


set_time_limit(0);

error_reporting(E_ALL ^ E_NOTICE);


$client = array();

$clientOut = array();

$sockClient = array();


$port = ($_GET['port']) ? $_GET['port'] : 1080;

$ip = ($_GET['ip']) ? $_GET['ip'] : '127.0.0.1';

define('br', "<br />\n");


function echo_flush($string) {

    echo str_replace(chr(0), '.', $string).br."\n";

    flush();

    ob_flush();

}


function Debug($data) {

    $pos = 0;

    for ($i = 0; $i <= strlen($data); $i+=16) {

        $eod = strlen(substr($data, $i)) - 1;

        if ($eod > 15) $eod = 15;

        for ($j = $i; $j <= $i + $eod; $j++) {

            $hex .= sprintf('%02.2s ', dechex(ord(substr($data, $j, 1))));

            $string .= replace(substr($data, $j, 1), '.', array(chr(0), chr(1), chr(9), chr(10), chr(11), chr(13)));

        }

        $pos = sprintf('%04.4s', empty($pos) ? '0' : $pos + 10);

        echo_flush($pos.': '.strtoupper(str_pad($hex, 48, '.. ')).$string);

        unset($hex, $string);

    }

}


function replace($string, $replace, $find) {

    for ($i = 0; $i < count($find); $i++) {

        $string = str_replace($find[$i], $replace, $string);

    }

    return $string;

}


function GetDWORD($string) {

    return (ord($string{0}) << 24) | (ord($string{1}) << 16) | (ord($string{2}) << 8) | ord($string{3});

}


function GetWORD($string) {

    return (ord($string{0}) << 8) | ord($string{1});

}


function MakeDWORD($long) {

    return chr(($long & 0xFF000000) >> 24).chr(($long & 0x00FF0000) >> 16).chr(($long & 0x0000FF00) >> 8).chr($long & 0x000000FF);

}


function MakeWORD($long) {

    return chr(($long & 0xFF00) >> 8).chr($long & 0x00FF);

}


function closeClient($i) {

    global $client, $sockClient;

    echo_flush("Closing client[$i] ({$client[$i][ip]}:{$client[$i][port]})\n");


    socket_close($sockClient[$i]);

    $sockClient[$i] = NULL;

    unset($client[$i]);

}


switch ($_GET['action']) {

    case 'start':

        $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('Unable to create server socket.');

        socket_bind($server, $ip, $port) or die("Server was unable to bind to $ip:$port.");

        socket_listen($server) or die('The server was unable to establish a listening state.');

        do {

            $rfds[0] = $server;


            foreach ($sockClient as $key => $value) if ($value) $rfds[$key + 1] = $sockClient[$key];

            $nready = socket_select($rfds, $write = NULL, $except = NULL, 0);


            if (in_array($server, $rfds)) {

                echo_flush("The server is setting up a new client.");

                $usekey = false;

                $foreach = false;

                $key = 0;

                foreach ($sockClient as $key => $value) {

                    $foreach = true;

                    if (!$value) {

                        $usekey = true;

                        break;

                    }

                }

                if (!$usekey && $foreach) $key++;

                $sockClient[$key] = socket_accept($server);

                socket_getpeername($sockClient[$key], $client[$key]['ip'], $client[$key]['port']);

                echo_flush("Accepted {$client[$key][ip]}:{$client[$key][port]} as client[$key]");

                if ($key > $maxi) $maxi = $key;

                if (--$nready <= 0) continue;

            }


            for ($i = 0; $i <= $maxi; $i++) {

                if (!$sockClient[$i]) continue;

                if (in_array($sockClient[$i], $rfds)) {

                    $n = @socket_read($sockClient[$i], 2048);

                    if (!$n) closeClient($i);

                    elseif ($client[$i]['ip'] == '127.0.0.1' && $n == 'kill') {

                        echo_flush('Kill signal received.');

                        exit;

                    } elseif ($client[$i]['connected']) {

                        socket_write($clientOut[$i], $n);

                    } else {

                        if (ord($n{0}) == 4 && ord($n{1}) == 1) {

                            echo_flush("Incoming CONNECT request from {$client[$i][ip]}:{$client[$i][port]}.");

                            $ip = long2ip(getDWORD(substr($n, 4, 4)));

                            $port = getWORD(substr($n, 2, 2));

                            $clientOut[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('Unable to create client outgoing socket.');

                            socket_connect($clientOut[$i], $ip, $port) or die('Unable to connect to that address');

                            socket_write($sockClient[$i], chr(0).chr(90).makeWORD($port).makeDWORD(ip2long($ip)));

                            echo_flush("Successfully established a connection to $ip:$port.");

                            $client[$i]['connected'] = true;

                        }

                    }

                }

            }


            unset($rfds);

            $rfds[0] = $server;

            foreach ($clientOut as $key => $value) if ($value) $rfds[$key + 1] = $clientOut[$key];

            $nready = socket_select($rfds, $write = NULL, $except = NULL, 0);

            if ($nready < 1) continue;


            for ($i = 0; $i <= $maxi; $i++) {

                if (!$clientOut[$i]) continue;

                if (in_array($clientOut[$i], $rfds)) {

                    $n = @socket_read($clientOut[$i], 2048);

                    if (!$n) closeClient($i);

                    else {

                        socket_write($sockClient[$i], $n);

                    }

                }

            }


            unset($rfds);

        } while(true);

        break;


    case 'stop':

        $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('Unable to create server socket.');

        socket_connect($server, $ip, $port) or die("No server is running at $ip:$port.");

        socket_write($server, 'kill');

        break;

}

?>


#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Very nice!

#3
Brandon W

Brandon W

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,828 posts
A description would be nice to add to it?
jQuery Selectors Tutorial - jQuery Striped Table tutorial - jQuery Events - jQuery Validation

Sorry if I don't post as often as I did, I'll try to get here as much as possible! I'm working my bum off to get this scholarship and other stuff!


#4
kiddies

kiddies

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts
can u give a alghorithm

#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
An algorithm for what?