PHP - Php Socket To Print To Networked Printer
Hi, I have been searching all day but can't find a solution to this using PHP.
Basically were developing a CRM at work and wish to be able to print letters remotely using PHP. We have a printer equipped with a network card and I want to be able to fire requests to a socket listener port and have it print template documents depending on the request. So far all I've found is something called Line Printing Terminal which apparently can be called from command line as far as I understand. My boss has currently had me code a VB.NET script with two browser windows and it refreshes every 30 seconds, gets a url from a div element in the page and prints the webpage but I don't like this way, I think it's a sloppy hack and wastes bandwidth. Like I say, ideally I would like to fire requests at a port via the printservers IP address but we could have the printer set as default on the server on which the printing script would run. Any help/advice or resources would be greatly appreciated. Similar TutorialsI am trying to print an image to a thermal POS printer from a PHP script. I have managed to get a text file to print by saving it to a file and copying to the USB port and that works fine. Am running PHP on Windows. Would appreciate any assistance. Thanks Steve my client changed their mind, and wants a field in the database that toggles to 'printed' if they've printed. I had a simple javascript that generates a button: Code: [Select] <style type="text/css" media="print"> @page { size:8.5in 11in; margin: 1cm } .printbutton { visibility: hidden; display: none; } </style> <script> document.write("<input type='button' " + "onClick='window.print()' " + "class='printbutton' " + "value='Print This Page'/>"); </script> But I'm assuming I ought to do this with php - or would it be jquery? , so that when they click the button, I can do a query update to the database. But I can't find any tutorials on it. Searching for it, just brings up the php command, "print" grrr. Alright so I've got some files being generated on the fly via database information. User clicks a button, which gathers that database information, puts it all into a file (*.tpl - which is really just an html page), then sends the file to the printer. Question is, how do I send the file to the printer queue of the computer that viewed the webpage? On a side note, is it easier/better to do the HTML layout or write a default.doc, then read that and copy the files to a new file and print that? or perhaps just hit a 'view & print' button, which opens up in a new window the size of the 'image' that needs to be printed, and have a print button on that page. Hello there, I have run into a problem. I have a search box, which searches through my database and gets results hopefully. But I need to be able to print the list. There is the problem. If I just print the page, it does not print the results. Here is the search.php with the php and the current print javascript. -Search By Address or Postcode-<br> <form name="search" method="post" action="search.php" id="searchform"> Query: <input type="text" name="name"> <input type="submit" name="submit" value="Search"></form> <br><br> -Search By REFID-<br> <form name="search2" method="post" action="search.php" id="searchform2"> Query: <input type="text" name="name2"> <input type="submit" name="submit2" value="Search"></form> <br><br> <?php if(isset($_POST['submit'])){ if($_POST['name'] > NULL){ $name=$_POST['name']; $sql="SELECT * FROM propertyaddress WHERE `address 1` LIKE '%" . $name . "%' OR `postcode` LIKE '%" . $name ."%'"; //-run the query against the mysql query function $result=mysql_query($sql); //-create while loop and loop through result set ?> <SCRIPT LANGUAGE="JavaScript"> if (window.print) { document.write('<form>' + '<br><input type=button name=print value="Print Results" ' + 'onClick="javascript:window.print()"></form>'); }</script> <script language="javascript" type="text/javascript"> <?php while($row=mysql_fetch_array($result)){ echo "<ul>\n"; echo '<a href="display.php?id='.$row['id'].'">'.$row['address 1'].', '.$row['address 2'].' at '.$row['postcode'].'</a><br>'; echo "</ul>"; } } else{ echo "<p>Please enter a search query</p>"; } } I'm at a lost. I'm not sure what to do, I don't think the code as anything to do with printing, but I put it there just in case. I thought about writing it to a temp html page in a popup, but I don't really no how to do that really well. I appreciate any help or suggestions you give.
According to I want ot run a websocket for PHP and javasscript.
How can I basic use websocket on it? Hallo i start learning Socket and php programming for now successfully manage to make the communication between the client and the server, by sending an automatic message from the system. I am interested in the following: 1. Does the server can send messages to specific client ? or server send to all client, and then client make filter of message (this is for me, this is not)? 2. How i can menage number of connection ? 3. How i can menage to make live client and server? I make while(true){ // code } part of code for make server live, but this way is not too functional, because the server does not see what was happening, I can see the response message to the client only PS: Is there any bether solution ? Hi I recently created a socket server in PHP and a client in actionscript, what the client does is send the X and Y and there ID to the server and then the server sends it back to the clients connected, my problem is it works but the X and Y start messing about and it duplicates sometimes, i'm pretty sure it is to do with the PHP server, this is my code: Server: Code: [Select] <?php /* Raymond Fain Used for PHP5 Sockets with Flash 8 Tutorial for Kirupa.com For any questions or concerns, email me at ray@obi-graphics.com or simply visit the site, www.php.net, to see if you can find an answer. */ // E_ALL is a named constant (bit of 2047) // error_reporting(E_ALL) ensures any errors will be displayed error_reporting(E_ALL); // set_time_limit() is set to 0 to impose no time limit set_time_limit(0); // ob_implicit_flush() will push the whole message to flash (including any extra markups like terminating zeros) ob_implicit_flush(); // address set to internal port for the socket to bind to and port set to something above 1024 so flash will connect $address = '192.168.1.71'; $port = 9999; //---- Function to Send out Messages to Everyone Connected ---------------------------------------- // $allclient is an array of resource id's that php will refer to for the sockets // $socket contains the resource id for the flash client who sent the message // $buf is just the message they sent, we are sending to everyone using a foreach loop function send_Message($allclient, $socket, $buf) { foreach($allclient as $client) { $phoneChunks = explode("=", $buf); $pid = $phoneChunks[0]; $x = $phoneChunks[1]; $y = $phoneChunks[2]; // socket_write uses the $client resource id (which calls on the socket) and sends it our message (which is the second flag) socket_write($client, "$pid=$x=$y"); echo "$pid=$x=$y \n"; } } //---- Start Socket creation for PHP 5 Socket Server ------------------------------------- // socket_create function is pretty simple, depending on what you want it to do, you can just rig it for that, // AF_INET is a "kind of" default address/protocol family that I have used, // then socket_create takes and uses SOCK_STREAM, another default available socket type, // and uses a SOL_TCP protocol to have a guaranteed data sending. if (($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { echo "socket_create() failed, reason: " . socket_strerror($master) . "\n"; } // this little beauty is hard to understand, but very useful to our kind of chat // we want to be able to reuse our sockets, so we set our $master socket with a level at SOL_SOCKET, // with it reusable (SO_REUSEADDR), and a "1" in the mixed optval spot to make it true. socket_set_option($master, SOL_SOCKET,SO_REUSEADDR, 1); // now we need to bind our socket to the address and port specified. if (($ret = socket_bind($master, $address, $port)) < 0) { echo "socket_bind() failed, reason: " . socket_strerror($ret) . "\n"; } // to allow our socket server to listen for incoming calls made by our flash client, we need // to use socket_listen on our $master socket. The next flag indicates that only 5 calls at a time. // any others will be refused until there is sufficient room to process a new call. if (($ret = socket_listen($master, 5)) < 0) { echo "socket_listen() failed, reason: " . socket_strerror($ret) . "\n"; } // this will allow an easy way to keep track of sockets connected to our server $read_sockets = array($master); //---- Create Persistent Loop to continuously handle incoming socket messages --------------------- while (true) { $changed_sockets = $read_sockets; // socket_select is used here to see if there were any changes with the sockets that were connected before // $num_changed_sockets is here so you can check to see if the change is true or not with a subsequent function $num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL); // we run a foreach function on $changed_sockets to see whether it needs to be added (if new), determine the message it sent // or determine if there was a socket disconnect foreach($changed_sockets as $socket) { // now if the $socket currently being checked is the $master socket, we need to run some checks // if not then we will skip down to else and check the messages that were sent if ($socket == $master) { // socket_accept will accept any incoming connections on $master, and if true, it will return a resource id // which we have set to $client. If this did not work then return an error, but if it worked, then add in // $client to our $read_sockets array at the end. if (($client = socket_accept($master)) < 0) { echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n"; continue; } else { array_push($read_sockets, $client); } } else { // socket_recv just receives data from $socket as $buffer, with an integer length of 2048, and a mystery flag set to 0 // that mystery flag has no real documentation so setting it to 0 will solve it as others have done. // we've also set it as a var $bytes in case we need to ensure data sending with socket_write, which is optional $bytes = socket_recv($socket, $buffer, 2048, 0); // if the $bytes we have is 0, then it is a disconnect message from the socket // we will just search for it as an index and unset that socket from our $read_sockets and // finish up with using socket_close to ensure it is closed off if ($bytes == 0) { $index = array_search($socket, $read_sockets); unset($read_sockets[$index]); socket_close($socket); }else{ // we need to make sure $read_sockets isn't messed with, so setting up a new variable called $allclients // will ensure this. We then shift the array so that our $master socket is not included to the count when // we send our data to all the other sockets in $allclients. $allclients = $read_sockets; array_shift($allclients); // just a simple call on our premade function 'send_Message' with $allclients, $socket (current one), and $buffer (the message) send_Message($allclients, $socket, $buffer); } } } } ?> This is my ActionScript 2, but I'm pretty sure this is not the problem: Code: [Select] _global.server_connected = false; _global.mySocket = new XMLSocket(); mySocket.onConnect = function(success) { if (success) { msgArea.htmlText += "<b>Server connection established!</b>"; server_connected = true; } else { msgArea.htmlText += "<b>Server connection failed!</b>"; } }; mySocket.onClose = function() { msgArea.htmlText += "<b>Server connection lost</b>"; }; //incoming data from server. var depthb = 6000; var myArray = new Array(); mySocket.onData = function(msg) { //msgArea.htmlText += msg; myArray = msg.split('='); if(_global.pid != myArray[0]) { if(_root["players_" + myArray[0]]) { //if players exist if(_root["players_" + myArray[0]]._x != myArray[1] || _root["players_" + myArray[0]]._y != myArray[2]) { _root["players_" + myArray[0]]._x = myArray[1]; _root["players_" + myArray[0]]._y = myArray[2]; } } else { _root.players.duplicateMovieClip("players_" + myArray[0], 6000); //_root["players_" + myArray[0]]._x = myArray[1]; //_root["players_" + myArray[0]]._y = myArray[2]; } } }; //connect to server. _global.mySocket.connect("192.168.1.71", 9999); If you are good with sockets and such then you should easily be able to spot the problem on why it's buggy, I cannot see what is wrong and really need the client and server to communicate properly. It's OK when you connect alone, but when someone else joins it will start being glitchy and not going to the correct X and Y and then there will be duplicates and such.. If you do not understand I will try and get a demo up and show you what I mean. Thanks. Hey, I've had this problem for a couple days now, and haven't been able to work it out. I'm trying to connect to the Gamesurge IRC using PHP - though the code I am using times out and can't connect. I thought it was my code, however I have searched the web for working codes and they all *seem* to do the same basic thing as mine. So if anyone has any ideas as to why I am getting a timeout, I would appreciate it. The code I'm using. <?php error_reporting(E_ERROR); $cfg = array( "server" => "irc.gamesurge.net", "channel" => "#wiremod", "port" => 6667, "name" => "thetree PHP" ); echo "Connecting to " . $cfg["server"] . " on port " . $cfg["port"] . "<br/>"; $socket = fsockopen($cfg["server"], $cfg["port"], $errno, $errstr, 5); if (!$socket) { echo("Error[$errno]: $errstr...<br/>"); } else { echo "Socket connection successful..<br/>"; } fclose($socket); ?> Hosted file: http://joethetree.lil.org.uk/socket.php Thanks thetree Can someone give me a simple socket script that I can copy and paste. It can return anything you like. I just want to make sure I have a working socket connection, and if not then you can maybe help me fix it. I am wondering if anyone has some useful PHP socket programming examples. There are a lot of tutorials out there but I find a lot of them are not well written and often are only written from either the client or server's point of view. I would really like to see a good example where two separate scripts are provided. 1. A Server Side to put on the one computer. 2. A Client Side to put on another computer. The best would be something super simple that says/sends... "Hello other world!" and the other side receives it, prints it to a file. This way people could clearly see the interaction and learn rather then geting half the story and trying to puzzle their way through things. Puzzling has is merits but now when you are a busy person. Hi, I am getting a couple of errors when running my php script PHP Error: 8: Undefined property: ***********::$xmltypehandlers, in ************* ←[32m[xmlServ:0] ←[33;1m[10:31:15]←[1m ←[37mStarted CPSM, version 0.04, Login Se rver communication mode: database ←[00m Connected to MySQL server localhost username *** PHP Error: 8: Use of undefined constant MSG_EOR - assumed 'MSG_EOR', in*******\ClientBase.php at 33! PHP Error: 2: socket_send() expects parameter 4 to be long, string given, in ******\ClientBase.php at 43! ←[32m[xmlServ:1] ←[33;1m[10:31:46]←[1m ←[37mClient created, ID:1, Socket ID: 0, rndK: ?NeR9X3lTWw←[00m PHP Error: 8: Use of undefined constant MSG_EOR - assumed 'MSG_EOR', in *********\ClientBase.php at 33! PHP Error: 2: socket_send() expects parameter 4 to be long, string given, in *********\ClientBase.php at 43! ←[32m[xmlServ:1] ←[33;1m[10:31:46] ←[35;1mMalformed packet <policy-file-request/ > sent by 0←[00m Since most of the errors originate in ClientBase.php Here is that File: Code: [Select] <?php class ClientBase{ static $num = 0; static $count = 0; public $properties = array(); public $p = null; public $sock; public $parent; public $room; public $uniqueid = 0; public $inGame = false; public $xpos = 0; public $ypos = 0; public $clientID = 0; public $name = ""; function __construct($sock, $server, $clientid){ self::$num++; self::$count++; $this->parent =& $server; $this->uniqueid = self::$count; $this->sock = $sock; $this->p =& $this->properties;//p and properties are for temporary properties. $this->p['rndK'] = $this->makeRndK(); $this->clientID = $clientid; } /*function __destruct(){ self::$num--; @socket_close($this->sock); }*/ function write($data, $flags = MSG_EOR){ $data .= chr(0); $sendLen = strlen($data); $w = array($this->sock); $a = null; $b = null; $res = @socket_select($a, $w, $b, 0.15); if($res === false){ return $this->parent->removeClient($this->clientid); } $len = @socket_send($this->sock, $data, $sendLen, $flags); //$times = 5; /*while($len === false && $len < $sendLen){ if($len === false){ $ltr = 0; } else $ltr = $len; $data = substr($data, $ltr); $sendLen = strlen($data); $len = @socket_send($this->sock, $data, $sendLen, $flags); usleep(2000); $times--; if($times < 0) break; }*/ return $len ? true : false; } function makeRndK(){ $c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789?~"; $l = rand(6,14); $s = ""; for(;$l > 0;$l--) $s .= $c{rand(0,strlen($c) - 1)}; return $s; } function buildClientString($type = "raw", $s = "%"){ if($type == "xml"){ return $this->buildXmlPlayer(); } return $this->buildRawPlayer($s); } function getSortedProperties(){ } function buildRawPlayer($s){ return implode($this->getSortedProperties(), $s); } function getSocket(){ return $this->sock; } } ?> Please Help, Thanks. If the first error means a lot I will post some of that file too. Hi everyone! I'm trying to create a socket TCP/IP server, i used this code which is already available @ php.net Code: [Select] <?php error_reporting(E_ALL); /* Allow the script to hang around waiting for connections. */ set_time_limit(0); /* Turn on implicit output flushing so we see what we're getting * as it comes in. */ ob_implicit_flush(); $address = '0.0.0.0; $port = 5000; if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == false) { echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "<br \>"; } if (socket_bind($sock, $address, $port) == false) { echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "<br \>"; } if (socket_listen($sock, 5) == false) { echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "<br \>"; } do { socket_set_nonblock($sock); if (($msgsock = socket_accept($sock)) == false) { echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "<br \>"; socket_clear_error(); break; } /* Send instructions. */ $msg = "\nWelcome to the PHP Test Server. <br \>" . "To quit, type 'quit'. To shut down the server type 'shutdown'.<br \>"; socket_write($msgsock, $msg, strlen($msg)); do { if (false == ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) { echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "<br \>"; break 2; } if (!$buf = trim($buf)) { continue; } if ($buf == 'quit') { break; } if ($buf == 'shutdown') { socket_close($msgsock); break 2; } $talkback = "PHP: You said '$buf'.<br \>"; socket_write($msgsock, $talkback, strlen($talkback)); echo "$buf<br />"; } while (true); socket_close($msgsock); } while (true); socket_close($sock); ?> I've assigned the address to receive from anybody '0.0.0.0' The problem is that it tells me: socket_accept() failed: reason: Success I searched a lot trying to figure this error out but found nothing. Any help, i'd be thankful? Hi, sorry for the crosspost - I'm new here, and obviously asked my question in the wrong part of the forum. Can anyone help out with this knotty little problem? http://www.phpfreaks.com/forums/index.php?topic=358418.0 TL;DR Do socket resources created by socket_accept take on the blocking properties of the master they were spawned from, or can you get granular control over them by calling socket_set_nonblock() on them individually? Hi, I'm extremely new to using sockets, but I think I have pretty straight-forward questions. What exactly is a "buffer"? I see people use a buffer and set a number for it (assuming size of the buffer... I guess?), but what's a good number to set it at then? I am trying to open as many sockets I can against my mail server to test if it is prown to attack. I have tried to create 2000 sockets, but I can't seem to get it working and wondering if anyone knows whats going on? <?php $counter = 0; createsocket: $socket = socket_create(AF_INET, SOCK_RAW, tcp); socket_connect($socket, "10.0.0.4", 25); $counter++; if ($counter != 2000) { goto createsocket; } sleep(240); socket_close($socket); ?> Hi all, i am running a php based virtual airline for a flightsimulator (free and open source) www.flightgear.org i am interested in creating a page where i can have members connect to the sim via localhost and port which will then read data sent from the sims internal server. i can send data via tcp by creating the port via the simulator I can create a protocol file so the server knows what data i am requesting (in the image above there is a protocol file "squawk" already requested. i know i can use fsocket_create etc or thats the theory. The socket would need to remain open from start to finish as data would be constantly changing. Any pointers would be appreciated. Thanks Alex Hello, I'm trying to update my database with current statistics from my gameservers, but running the loop of socket connections to all of the servers on page load takes too long. For every server in the array it takes roughly 4 seconds to complete each one.. with a massive list of say 42 it takes awhile. However, I'm running from shared hosting and was wondering if that was the reason each server takes so long to query. I was thinking about running a cron job every 1 minute to update the information so it's still relativity new and current. Will the 1 minute cron job affect anything from the shared hosting? I'm using 1and1 web-hosting on a 1&1 Business Package. Thanks Hi, i'm developing an app in wampp, i'm usually use cUrl but this time i wanted to try sockets for a change and more portability. I have followed the basic socket structure but i can't connect. So this is my code: Code: [Select] function googlear($search,$filtro,$safe) { //Abrimos el socket $socket = fsockopen( "www.google.com", 80, $errno,$errdesc); if (!$socket) {print "$errstr ($errno)<br/>\n";die;}; $busqueda = "search?q=".$search."&num=100";//Solo me va a tirar 100 resultados por ahora, para ir pasando de pagina arranco de start=0 y voy sumando de a 100 para pasar de pagina. if($safe = true) { $busqueda = $busqueda . "&safe=active"; } if($filtro != true) { $busqueda = $busqueda . "&filter=0"; } $request = "GET $busqueda HTTP/1.1\r\n"; $request .= "Host: www.google.com\r\n"; $request .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\r\n"; $request .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"; $request .= "Accept-Language: es-ar,es;q=0.8,en-us;q=0.5,en;q=0.3"; $request .= "Accept-Encoding: gzip, deflate\r\n"; $request .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"; $request .= "Connection: keep-alive\r\n"; //Mando las cabeceras con el socket como resource fputs($socket, $request); while(!feof($socket)) { $busqueda[] = fgets($socket, 1024); } //Cerramos fclose($socket); return count($busqueda); } As you can see i'm doing a GET and waiting for the count of lines of the array as result (just to test), but i'm getting "Fatal error: Maximum execution time of 30 seconds exceeded in [...]". It can't take that long to make a GET Request... Any clues? Hi. I've tried just about everything I can think of, but no success. Here's the perl I'm trying to convert: $socket = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => 1500, Proto => 'tcp'); if ($socket->send("$token\n")) { $data = <$socket>; } Here's what I've currently got in PHP: $socket = fsockopen('localhost', 1500, $errno, $errstr); fwrite($socket, "$token\n"); $data = fread($socket, 1024); fclose($socket); I've confirmed the socket descriptor is populated and the fwrite is working. The fread just hangs. I've tried fputs/fgets in various combinations, but the read/get always hangs. Any ideas? Thanks very much, Rick Hello guys, I'm trying to learn and understand the process of connecting a client to TCP connection! Now I'm trying to build a mobile chat application which I want it to connect to my server (hosted in media temple) which I hate about media temple is the way they name the variable we used to know like "localhost" to some random strange string! anyway that's not the topic. But you got the idea it's a chat app as the client on a mobile device! that will try to connect to my server. Now I have tried sooo many scripts, tutorials ... etc. But I didn't get it. I need to know the process or even get it to work so I'll be able to know what's going on from the code. Here's what I have (as of now) on the mobile (client side): // create the socekt object var socket = Titanium.Network.createTCPSocket({ hostName:"mywebsite.com", port:4446, // some port I just typed because I don't know what port! mode:Titanium.Network.READ_WRITE_MODE }); // connect button connectBtn.addEventListener('click', function() { if(socket.isValid == false){ try { socket.connect(); socket.listen(); messageLabel.text = 'Opened!'; } catch (e) { messageLabel.text = 'Exception: '+e; } } }); // reader listener socket.addEventListener('read', function(e) { Ti.API.info(JSON.stringify(e)); Ti.API.info(e['from'] + ':' + e['data'].text); }); //writer button writeButton.addEventListener('click', function() { try { socket.write("writing...this"); } catch (e) { alert(e); } }); //## //## Credits goes to people in: http://www.functionblog.com/?p=67=1#viewSource //## <?php // PHP SOCKET SERVER error_reporting(E_ERROR); // Configuration variables $host = "127.0.0.1"; $port = 4041; $max = 20; $client = array(); // No timeouts, flush content immediatly set_time_limit(0); ob_implicit_flush(); // Server functions function rLog($msg){ $msg = "[".date('Y-m-d H:i:s')."] ".$msg; print($msg."\n"); } // Create socket $sock = socket_create(AF_INET,SOCK_STREAM,0) or die("[".date('Y-m-d H:i:s')."] Could not create socket\n"); // Bind to socket socket_bind($sock,$host,$port) or die("[".date('Y-m-d H:i:s')."] Could not bind to socket\n"); // Start listening socket_listen($sock) or die("[".date('Y-m-d H:i:s')."] Could not set up socket listener\n"); rLog("Server started at ".$host.":".$port); // Server loop while(true){ socket_set_block($sock); // Setup clients listen socket for reading $read[0] = $sock; for($i = 0;$i<$max;$i++){ if($client[$i]['sock'] != null) $read[$i+1] = $client[$i]['sock']; } // Set up a blocking call to socket_select() $ready = socket_select($read,$write = NULL, $except = NULL, $tv_sec = NULL); // If a new connection is being made add it to the clients array if(in_array($sock,$read)){ for($i = 0;$i<$max;$i++){ if($client[$i]['sock']==null){ if(($client[$i]['sock'] = socket_accept($sock))<0){ rLog("socket_accept() failed: ".socket_strerror($client[$i]['sock'])); }else{ rLog("Client #".$i." connected"); } break; }elseif($i == $max - 1){ rLog("Too many clients"); } } if(--$ready <= 0) continue; } for($i=0;$i<$max;$i++){ if(in_array($client[$i]['sock'],$read)){ $input = socket_read($client[$i]['sock'],1024); if($input==null){ unset($client[$i]); } $n = trim($input); $com = split(" ",$n); if($n=="EXIT"){ if($client[$i]['sock']!=null){ // Disconnect requested socket_close($client[$i]['sock']); unset($client[$i]['sock']); rLog("Disconnected(2) client #".$i); for($p=0;$p<count($client);$p++){ socket_write($client[$p]['sock'],"DISC ".$i.chr(0)); } if($i == $adm){ $adm = -1; } } }elseif($n=="TERM"){ // Server termination requested socket_close($sock); rLog("Terminated server (requested by client #".$i.")"); exit(); }elseif($input){ // Strip whitespaces and write back to user // Respond to commands /*$output = ereg_replace("[ \t\n\r]","",$input).chr(0); socket_write($client[$i]['sock'],$output);*/ if($n=="PING"){ socket_write($client[$i]['sock'],"PONG".chr(0)); } if($n=="<policy-file-request/>"){ rLog("Client #".$i." requested a policy file..."); $cdmp="<?xml version=\"1.0\" encoding=\"UTF-8\"?><cross-domain-policy xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd\"><allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\" /><site-control permitted-cross-domain-policies=\"master-only\" /></cross-domain-policy>"; socket_write($client[$i]['sock'],$cdmp.chr(0)); socket_close($client[$i]['sock']); unset($client[$i]); $cdmp=""; } } }else{ //if($client[$i]['sock']!=null){ // Close the socket //socket_close($client[$i]['sock']); //unset($client[$i]); //rLog("Disconnected(1) client #".$i); //} } } } // Close the master sockets socket_close($sock); ?> I just want to understand how am I gonna implement this! I need to know how does it work! You help is much appreciated! |