PHP - Irc Socket Connect
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 Similar TutorialsHi, 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? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=319948.0 hi all, i have a test server (newest xampp) and the code works fine, as soon as i upload to 1and1 (they use apachi, php and mysql) i get this message: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) i have double checked username and passwords, had a look on google, contacted there support with no luck yet. i am wondering if its a mysql or php version problem, so hoping someone knows when the following code with classes etc was added or if someone knows how to fix it i be really greatful. heres some of the code i am using class cyberglide { var $host; var $username; var $password; var $db; function connect() { $con = mysql_connect($this->host, $this->username, $this->password) or die (mysql_error()); mysql_select_db($this->db, $con) or die(mysql_error()); } function get_top() { if (isset($_GET['page'])) { $page = $_GET['page']; // Display Page. $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } else { //Show Home Page $sql = "SELECT title,body FROM content WHERE page = 'home' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } } function get_left() { if (isset($_GET['page'])) { $page = $_GET['page']; // Display Page. $sql = "SELECT title,body FROM content WHERE page = '$page' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } else { //Show Home Page $sql = "SELECT title,body FROM content WHERE page = 'home' AND location = 'left' AND disabled = 'no' ORDER BY id"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ echo '<h1>' . $row['title'] . '</h1>'; echo '<p>' . $row['body'] . '</p>'; } } } }//Ends Our Class db file //Setup Our Connection Vars $obj->host = 'localhost'; $obj->username = 'root'; $obj->password = ''; $obj->db = 'db361371865'; //Connect To Our Database $obj->connect(); many thanks all.
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'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 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, 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? 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); ?> 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. 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 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. 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 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! 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'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 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=312186.0 I have a hosted VPS running PHP 7.3.5 and a local RPi running 7.0.33, and will refer to them as VPS and RPi. I also have the following very basic socket client and server. The server on the VPS and the client on the RPi using TCP works great and so does both the server and the client on the VPS using TLS. But when I put the server on the VPS and the client on the RPi using TLS, I can only send relatively short packages (approximately 2,600 characters). And there is no hard limit because one moment 2,628 characters works, but then a little later 2,619 will not. Does it look like something I am doing wrong or maybe upgrading PHP on the RPi will help? Thank you <?php require 'simple_common.php'; $loop = React\EventLoop\Factory::create(); $connector = new React\Socket\Connector($loop); logger("simple client is running using ".($tls?'tls':'tcp')); if($tls) { $sslContextOptions = [ 'peer_name'=> get('peer_name'), //'verify_peer'=>false, //'verify_peer_name'=>false, 'allow_self_signed'=>true, 'cafile' => get('cafile'), //Certificate Authority file used with verify_peer. Use public cert since selfsigned? //'verify_depth' not set and defaults to none //'ciphers' not used and defaults to DEFAULT //'capath'=>null, //Not needed since cafile is given //'CN_match' and 'SNI_server_name' are depreciated and peer_name should be used instead. ]; $connector = new React\Socket\SecureConnector($connector, $loop, $sslContextOptions); } $connector->connect(get('ipPort'))->then(function (React\Socket\ConnectionInterface $connection) use ($loop) { logger("onConnection"); setEvents($connection, 'client'); $string=str_repeat(substr(str_repeat('0123456789',10),0,-1), 26).'023456789023456789023456789023456789023456789023456789'; logger("write strlen: ".strlen($string)); logData('write', $string); $connection->write($string); }); $loop->run(); <?php require 'simple_common.php'; $loop = React\EventLoop\Factory::create(); logger("simple server is running using ".($tls?'tls':'tcp')); $socket = new React\Socket\Server(get('ipPort'), $loop); if($tls) { $sslContextOptions = [ 'local_cert' => get('local_cert'), //local certificate file w/ or w/o private key 'local_pk' => get('local_pk'), //Only needed if private key is not in local_cert //'passphrase' not set as local_cert is not encoded //'capture_peer_cert'=>true, //a peer_certificate context option will be created containing the peer certificate //'capture_peer_cert_chain'=>true, //a peer_certificate_chain context option will be created containing the certificate chain. //'SNI_enabled'=>true, //server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address. //'disable_compression'=>true, //disable TLS compression. This can help mitigate the CRIME attack vector. //'peer_fingerprint'=>[] //A hash or array of hashes which the remote certificate digest must match. ]; $socket = new React\Socket\SecureServer($socket, $loop, $sslContextOptions ); } $socket->on('connection', function (React\Socket\ConnectionInterface $connection) use ($loop) { logger('onConnection'); setEvents($connection, 'server'); $loop->addPeriodicTimer(1, function ($timer) use ($connection) { $data='Hello!'; logData('write', $data); $connection->write($data); }); }); $socket->on('error', function (\Exception $e) { logger('onServerError: '.$e->getMessage()); }); $loop->run(); <?php function setEvents($connection, string $type){ $connection->on('data', function ($data)use($type) { static $totalLng=0; $curLng=strlen($data); $totalLng+=$curLng; logger("$type onData: current: $curLng total: $totalLng"); logData('read', $data); }); $connection->on('error', function (\Exception $e)use($type) { logger("$type onError: ".$e->getMessage()); }); $connection->on('close', function()use($type) { logger("$type onClose"); }); $connection->on('end', function()use($type) { logger("$type onEnd"); }); $connection->on('drain', function()use($type) { logger("$type onDrain"); }); $connection->on('pipe', function()use($type) { logger("$type onPipe"); }); } function emptyLog($type){ $f = @fopen(get($type), "r+"); if ($f !== false) { ftruncate($f, 0); fclose($f); } } function logData($type, $string){ file_put_contents(get($type), $string, FILE_APPEND); } function logger($msg){ echo($msg.PHP_EOL); syslog(LOG_INFO, $msg); } function get($name){ $map = [ 'ipPort'=>'184.154.134.91:1338', 'peer_name'=>'tapmeister.com', 'cafile'=>'test_ss_crt.pem', //Use public cert since selfsigned? Why does even test_ss_csr.pem work? 'local_pk'=>'test_ss_key.pem', 'local_cert'=>'test_ss_crt.pem', //Why does even test_ss_csr.pem work? 'read'=>'raw_read_stream.log', 'write'=>'raw_write_stream.log', 'tls'=>true, ]; if(!isset($map[$name])) exit("Invalid name $name"); return $map[$name]; } ini_set('display_startup_errors', '1'); ini_set('display_errors', '1'); error_reporting(E_ALL); require 'vendor/autoload.php'; $tls=$argv[1]??get('tls'); emptyLog('write'); emptyLog('read');
|