PHP - Looping Socket Connections
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 Similar TutorialsOn my new site on average every page that loads opens 9 MySql connections and runs 14 MySql Queries, And as I use Ajax to dynamically update the pages, so this repeats every 60 seconds per page. Is this too many connections? I am not having any problems at the moment but the site is getting more busy, and I don't want the site to start running slow, or the MySql server to crash. Any comment would be much appreciated. Hi, I would just like to know what limitations apply for opening X amount of connections to different websites with Curl? (specifically, I'm using Curl multi and have my own way of regulating how many connections occur at a given time). I ask this because it seems I can open 100 connections and get the info from the websites quite quickly. If I were to open say 1000 would that crash my router or what would happen? Thanks in advance! Wasn't really sure what to call this topic, and I'm also not sure how to ask this question. Here is what I have, and the problem I'm having. I have an html form on a webpage that sends information into 2 different tables in a database I have. One table is not important to the topic, the other table is where i'm having my problem. The user submits their information from the form and the info goes into the tables. There is another page that displays the names of the users on a "wall" that populates from the second table in the database. The second table takes information from the form they filled out and displays their name on the wall based on that (most importantly whether or not they can be e-mailed from the wall or not). The issue I am having (and this is probably the long way of asking this) is that when some people fill out the form their info does not go into either database. I know the functionality works, because their have been a couple of users that have signed up and everything worked fine for them. I'm thinking this may be a connection issue possibly due to a firewall or something. Any ideas on this? The website is http://itgetsbetter.tsagl.org the form to fill out is under the button "Take the Pledge" and the names are displayed under "View the Wall". If someone wouldn't mind to try out the functionality of the form for me (I need people that have some technical experience to do this because most of the people that I work with have no idea what I am talking about when trying to troubleshoot this with them). I assure you that if everything works, I will remove your information from my database. This site is only out to a few people at the moment, but I am planning on taking it public in the next couple of days. I would display code here, but I'm not sure what code you would need to see in order to help with this. I just think this is a connection issue; I just need to know how to test it or how to rectify the issue. Thanks for your help (and please don't hate too much on the design on the site; i'm more of a programmer than a designer). 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 ?
According to I want ot run a websocket for PHP and javasscript.
How can I basic use websocket on it? At the moment I am writing an application that supports plugins. Every plugin implements an interface so that the main application can control the plugin with the interface methods. There could be plugins that need a database connection and others that do not. What I am doing at the moment is loading every plugin with a __construct($databaseHandler). For plugins that don't need a database connection this is a little overhead. I could also use a Singleton or something else "staticish" so that the plugin can get the database instance whenever it wants, but then the plugin can only be used for my application where this specific Singleton is present and maybe I would like to use the plugin for other purposes later in another environment without changing it. Do you have any better ideas or how do you normally manage your database connections? Hi, Just a quick query. I call my db connection and configuration files on every script. I also have just made a functions script where i'm storing some functions except when i call the function, my script fails because of a missing database connection. But on the page that fails, i call the configuration files including the db connection at the start of the script. But when i get to where i include the function they are all on the same script so should it fail?? The page did work fine when the function was inbedded in the script. But as i'm using the function on a few pages, i thought it would be better practise and more efficent to just include the function on each page i need, rather than just copy and paste all the php in the required pages. Or do i have to declare the db connection inside the function page as well??? Thanks I've looked every where, probably googled every variation of my question I could come up with and I've tried all of the suggestions... I'm trying to connect to two different DBs in two different locations ($local and $remote) and only the second one works. Here is a sample of my code ("..." = hidden): //-------------Local DB Connection: $local = mysql_connect("localhost","root","..."); if (!$local) { die('Could not connect: ' . mysql_error()); } $sel1 = mysql_select_db("new", $local); //-------------Remote DB Connection: $remote = mysql_connect("...","...","...",true); if (!$remote) { die('Could not connect: ' . mysql_error()); } $table = "..."; //---------function selecting from local: function fncGrabNemsis($ele,$val){ mysql_select_db("new", $local); $result = mysql_query("SELECT * FROM new.tblvalues WHERE fldelement='$ele' AND fldcode='$val'",$local); $tmprow = mysql_fetch_array($result); return (isset($tmprow['fldvariable'])?$tmprow['fldvariable']:$val); } //----------Select run from Remote: mysql_select_db("ImdxTest", $remote); $result = mysql_query("SELECT * FROM ImdxTest.$table WHERE ClientID = ... AND IncidentNum = '$fldINCID'", $remote) or die(mysql_error()); $row = mysql_fetch_array($result); I've tried moving the mysql_select_db() function calls everywhere you can think of and just about everything else... What happens is, I get php errors saying that $local is not defined or that the mysql function that are trying to use the $local connection are expecting parameters to be resources!? I know for a fact that both connections work because individually they both work. Only the second connection ($remote) works... Thanks a lot for any suggestions! Hey, I would there be a way i could create a form in which upon entering a domain name/URL it will tell you how many connections there are to the site and how many (if any) MySQL queries are running? If I add this line to a wordpress footer it displays the number of sql queries. Code: [Select] <?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds. Any help is greatly appreciated. Thanks. Hi everybody, I am facing "Too many connections" problem on my site. in fact the server is moved from one location to,another and after the movement this problem arise... Pls help. Thanks OK, so I dont think this is a code issue as such, but I am completely stumped as to where the issue could be. I have a page with some standard include() functions at the top. When I access the page from home, everything operates as it should, when I access it from work (on multiple machines), I get the standard "unable to open stream" and "unable to access" warnings for the include statements. I have tried hard refreshing and deleting cache (not that it should make a shred of difference) etc, but the error is still there after a week or so. Does anyone know what could be causing this issue? Hello guys, I hope you can help. I can't get my page to switch between two database connections properly It seems to ignore the second connection. I'm trying to go through each group in database one and find out how many members they have registered in database two by checking the field "tsName". This is a valid query for database one. $fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); This is a valid query for database two. $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); However despite me specifying which database link to use it tries to use every query on database one ($con1). So I can never query database two ($con2) because it just breaks with the result below. :S $fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); gives Quote AREA 43 [A-43] (11): result result result (there are 3 groups in database one) But: $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); gives Quote AREA 43 [A-43] (11): Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/sever/public_html/mav/tools/ts_corp_registrations.php on line 51 <?php // ===== Connect to database one (group) ===== $con1 = mysql_connect($db_host,$db_corps_user,$db_corps_pass); if (!$con1) { die("Could not connect:" . mysql_error()); } $db_select1 = mysql_select_db($db_corps_db, $con1); if (!$db_select1) { die ("Could not select database:" . mysql_error()); } // ===== Connect to database two (members) ===== $con2 = mysql_connect($db_host,$db_ts_user,$db_ts_pass, true); if (!$con2) { die("Could not connect:" . mysql_error()); } $db_select2 = mysql_select_db($db_ts_db, $con2); if (!$db_select2) { die ("Could not select database:" . mysql_error()); } $fetchCorps = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); while ($row = mysql_fetch_array($fetchCorps)) { // For each of the results, gather details from database one, then see how many members we can find in database two $cName = $row["cName"]; $cTicker = mysql_real_escape_string($row["cTicker"],$con1); $cMembers = $row["cMembers"]; echo $cName." [".$cTicker."] (".$cMembers."):<br />"; // ========================== HERE BE PROBLEMS ========================== //$fetchUsers = mysql_query("SELECT * FROM $db_corps_table ORDER BY cName;", $con1); $fetchUsers = mysql_query("SELECT * FROM 'users' WHERE tsName LIKE $cTicker%;", $con2); // =================================================================== while ($rowTS = mysql_fetch_array($fetchUsers)) { echo "result<br />"; } } // all done, close DB connections mysql_close($con2); mysql_close($con1); ?> Hi, I am quite new to using php classes so it maybe something simple here, however I am trying to establish to connection to two different databases using one PHP class; The problem is that this will work for one but when I create a new connection they will both fail.
<?php putenv("TZ=Europe/London"); // start database connection $funky_db = new Database('xxxx', 'xxxx', 'xxxx', 'xxxx'); // start database connection $funky_cc = new Database('xxxx', 'xxxx', 'xxxx', 'xxxx'); class Database { private $host; private $user; private $pass; private $name; private $link; private $error; private $errno; private $query; function __construct($host, $user, $pass, $name = "", $conn = 1) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; if (!empty($name)) $this -> name = $name; if ($conn == 1) $this -> connect(); } function __destruct() { @mysql_close($this->link); } public function connect() { if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass, TRUE)) { if (!empty($this -> name)) { if (!mysql_select_db($this -> name)) $this -> exception("Could not connect to the database!"); } } else { $this -> exception("Could not create database connection!"); } } public function close() { @mysql_close($this->link); } public function query($sql) { if ($this->query = @mysql_query($sql)) { return $this->query; } else { $this->exception("Could not query database!".$this->name); return false; } } public function num_rows($qid) { if (empty($qid)) { $this->exception("Could not get number of rows because no query id was supplied!"); return false; } else { return mysql_num_rows($qid); } } public function fetch_array($qid) { if (empty($qid)) { $this->exception("Could not fetch array because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid); } return $data; } public function fetch_array_assoc($qid) { if (empty($qid)) { $this->exception("Could not fetch array assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid, MYSQL_ASSOC); } return $data; } public function fetch_object($qid) { if (empty($qid)) { $this->exception("Could not fetch object assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_object($qid); } return $data; } public function fetch_all_array($sql, $assoc = true) { $data = array(); if ($qid = $this->query($sql)) { if ($assoc) { while ($row = $this->fetch_array_assoc($qid)) { $data[] = $row; } } else { while ($row = $this->fetch_array($qid)) { $data[] = $row; } } } else { return false; } return $data; } public function last_id() { if ($id = mysql_insert_id()) { return $id; } else { return false; } } private function exception($message) { if ($this->link) { $this->error = mysql_error($this->link); $this->errno = mysql_errno($this->link); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } if (PHP_SAPI !== 'cli') { ?> <div class="alert-bad"> <div> Database Error </div> <div> Message: <?php echo $message; ?> </div> <?php if (strlen($this->error) > 0): ?> <div> <?php echo $this->error; ?> </div> <?php endif; ?> <div> Script: <?php echo @$_SERVER['REQUEST_URI']; ?> </div> <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?> <div> <?php echo @$_SERVER['HTTP_REFERER']; ?> </div> <?php endif; ?> </div> <?php } else { echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n"; }; } } ?> Hi Have an issue with a script that connects to multiple Access databases to extract data. There is one master database and then numerous small databases (I take no responsibility for the design!). The master is opened and then the sub databases are looped around, opened process and closed in turn. However after about 20 connections I get the error [ODBC Microsoft Access Driver] Too many client tasks for any new connections. It is related to the number of connections rather than the number of operations on databases (ie, if I comment out one of the pieces of SQL run on each database it makes no difference). I am closing the connection and unsetting the variable that stores the connection. As such there shouldn't be an excess of connections open at any one time. Any suggestions? All the best Keith I was curious.. I read that after using a PDO connection you should set the object to null to close it out. In this instance: Code: [Select] function IsOwner($regionid, $user) { global $Username, $SQL_Server, $SQL_User, $SQL_Pass; $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass); $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user)); if ($sql->rowCount() == 0) { return false; } else { return true; } $pdo = null; } Since the return is called prior to the nulling, does it leave a connection hanging or does PHP do some sort of auto-closeout when a function ends? Should I instead be doing: Code: [Select] function IsOwner($regionid, $user) { global $Username, $SQL_Server, $SQL_User, $SQL_Pass; $ownerstatus = false; $pdo = new PDO("mysql:host=$SQL_Server;dbname=$SQL_Database", $SQL_User, $SQL_Pass); $sql = $pdo->prepare("SELECT count(region_id) FROM region_players WHERE region_id = ? AND user_id = ? AND owner = 1"); $sql->execute(array($regionid, $user)); if ($sql->rowCount() > 0) $ownerstatus = true; $pdo = null; return $ownerstatus; } ? 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 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. 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? 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? |