Getting a HeartBeat from a C# Application and Posting it To Website - php

I've got a Minecraft Software written in C# that I want to send a heartbeat to my site. I've got the way to send the beat already written.
if (Server.Uri == null) return;
string uri = "http://GemsCraft.comli.com/Heartbeat.php";
// create a request
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(string.Format("ServerName={0}&Url={1}&Players={2}&MaxPlayers={3}&Uptime={4}",
Uri.EscapeDataString(ConfigKey.ServerName.GetString()),
Server.Uri,
Server.Players.Length,
ConfigKey.MaxPlayers.GetInt(),
DateTime.UtcNow.Subtract(Server.StartTime).TotalMinutes));
request.ContentType = "application/x-www-form-urlencoded";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.ContentLength = postBytes.Length;
request.Timeout = 5000;
Stream requestStream = request.GetRequestStream();
// send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Flush();
requestStream.Close();
/* try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Logger.LogToConsole(new StreamReader(response.GetResponseStream()).ReadToEnd());
Logger.LogToConsole(response.StatusCode + "\n");
}
catch (Exception ex)
{
Logger.LogToConsole("" + ex);
}*/
}
Now, I want to be able to retrieve the heartbeat in PHP, upload it to the SQL database, and then display each user's server in a table that will be displayed on the webpage
How do I do this?

portforwardpodcast's answer isn't very well-suited for your purposes, here's a process for you to ponder
Server accesses the following page: heartbeat.php?port=25565&maxplayers=25&players=2&name=Cheese_Pizza_Palace
Your PHP script will then do the following...
Go through each value, making sure they're all the types you want them to be (integers/strings)
Connect to the database
Update the server in the database if it already exists, create it if it doesn't
Return some value so the server knows that it completed successfully.
And to display the servers
Fetch all 'active' servers
Loop through them and display each one.
Things you'll need to figure out:
How to determine uptime
How to determine "active" servers
How to update/create MySQL entries
How to (properly) connect to a database. I would suggest using PDO since you're using PHP. It's a bit difficult to learn, but it's much more secure than writing the queries directly.
How to loop through all the GET variables.
Good hunting!

I would create a simple php page accept a get variable. something like www.site.com/beat.php?lasttime=123456&serverid=1 where the number us the unix timestamp. Then you need to re-work your c# to do a simple get request on a website. Finally your php should insert into a mysql table with a column for id, timestamp, server_id etc.
First you need to pull the data from the request. The $_REQUEST variable in php is nice because it works for both GET and POST:
http://php.net/manual/en/reserved.variables.request.php
Start out by var_dump or echo the fields you want. Once you can get the needed data into variables you are done with the first part. For the next part you need to create a database and table in MySQL. The best tool for this is phpmyadmin. If you have a host like godaddy (or some others) you can get at this from the control panel. If not you may need to install upload the phpmyadmin files yourself. It's a pretty simple tool to use:
http://www.youtube.com/watch?v=xxQSFHADUIY
Once your database has the correct columns, you need to insert the data from your php file. This page should help:
http://www.w3schools.com/php/php_mysql_insert.asp

Related

Temporary storage on a server

I'm looking for an efficient and secure way to store small amount of user data like a line of text, for an indefinite period of time.
The scenario: One client 'A' sends some data to another client 'B' , asynchronously via a server 'S'. For simplicity, consider the data to be a single line of text. Now, this data would be delivered to client 'B' by server 'S' , only when B asks for it. So until that time Server 'S' has to store this data.
For a simple demo, I implemented it very crudely as follows: Client 'A' does a POST request with XMLHttpRequest, sending the text to 'S' as follows
xhr.open("POST",url+"?sentText=text"); //url points to a php file on S
xhr.send();
The PHP code then saves the received text to a file as follows:
<?php
$selected = $_GET["sentText"];
$writefile = "text.txt";
$fh = fopen($writefile,'w');
fwrite($fh,$selected);
fclose($fh);
?>
Later, after any amount of time, B asks for the text in this file,using BufferedInputStream as follows:
URL fileurl = new URL("url/text.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fileurl.openStream()));
while((tmpReceived = in.readLine())!=null){
received = tmpReceived;
}
This demo works properly, but this is just a demo. However, if this were to be a full scale real world application with millions of users, how would I implement the following:The part where server S stores the text. Obviously, I can't save the text as plain text in a file, as it would breach my users' privacy. And it would also be ineffecient when there are millions of users. How do commercial services like Dropbox achieve this?
To keep things simple, I just need to know how to do this for text, then I can extrapolate to other types possibly.
Thanks a lot!

Long polling - Message system

I'm looking into doing some long polling with jQuery and PHP for a message system. I'm curious to know the best/most efficient way to achieve this. I'm basing is off this Simple Long Polling Example.
If a user is sitting on the inbox page, I want to pull in any new messages. One idea that I've seen is adding a last_checked column to the message table. The PHP script would look something like this:
query to check for all null `last_checked` messages
if there are any...
while(...) {
add data to array
update `last_checked` column to current time
}
send data back
I like this idea but I'm wondering what others think of it. Is this an ideal way to approach this? Any information will be helpful!
To add, there are no set number of uses that could be on the site so I'm looking for an efficient way to do it.
Yes the way that you describe it is how the Long Polling Method is working generally.
Your sample code is a little vague, so i would like to add that you should do a sleep() for a small amount of time inside the while loop and each time compare the last_checked time (which is stored on server side) and the current time (which is what is sent from the client's side).
Something like this:
$current = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$last_checked = getLastCheckedTime(); //returns the last time db accessed
while( $last_checked <= $current) {
usleep(100000);
$last_checked = getLastCheckedTime();
}
$response = array();
$response['latestData'] = getLatestData() //fetches all the data you want based on time
$response['timestamp'] = $last_checked;
echo json_encode($response);
And at your client's side JS you would have this:
function longPolling(){
$.ajax({
type : 'Get',
url : 'data.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
var jsonData = eval('(' + data + ')');
//do something with the data, eg display them
timestamp = jsonData['timestamp'];
setTimeout('longPolling()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
alert(error);
setTimeout('longPolling()', 15000);
}
});
}
Instead of adding new column as last_checked you can add as last_checked_time. So that you can get the data from last_checked_time to the current_time.
(i.e) DATA BETWEEN `last_checked_time` AND `current_time`
If you only have one user, that's fine. If you don't, you'll run into complications. You'll also run one hell of a lot of SELECT queries by doing this.
I've been firmly convinced for a while that PHP and long polling just do not work natively due to PHP not having any cross-client event-driven possibilities. This means you'll need to check your database every second/2s/5s instead of relying on events.
If you still want to do this, however, I would make your messaging system write a file [nameofuser].txt in a directory whenever the user has a message, and check for message existence using this trigger. If the file exists and is not empty, fire off the request to get the message, process, feed back and then delete the text file. This will reduce your SQL overhead, while (if you're not careful) increasing your disk IO.
Structure-wise, an associative table is by far the best. Make a new table dedicated to checking the status, with three columns: user_id message_id read_at. The usage should be obvious. Any combination not in there is unread.
Instead of creating a column named last_checked, you could create a column called: checked.
If you save all messages in the database, you could update the field in the database. Example:
User 1 sends User 2 a message.
PHP receives the message using the long-polling system and saves the message in a table.
User 2, when online, would send a signal to the server, notifying the server that User 1 is ready to receive messages
The server checks the table for all messages that are not 'checked' and returns them.

Counter in ActionScript 3.0 with...PHP or?

I am doing this flash banners for multiple clients and one major request is to have some sort of counter so they know how many times the banner has been clicked.
I know how to do it in ActionScript 3.0, I make a simple var:int and i increase it +1 when a click is made on the banner. What do I do with the value of this var(say its 121) where do I store it online so its safe and can be changed by multiple flash banners(as3).
But how do I save this information so next time when the banner is loaded(on diffrent webpages) the number of clicks is whatever it was last time it was loaded.
Should I look into PHP for that ? I have no clue how to do this... some examples, tutorials, whatever works... would be much appreciated.(I am a designer, not programmer...please dont speak php-ish, or you know... :D)
I've googled a bit, and found some help, but i am still confused, and much of it its not AS3, I'm thinking maybe stuff has evolved a bit since the stuff that I found(2008)...
Thank you very much.
You'd have to store (and fetch) the value somewhere - either in the DB, in a text-file, ...
I'd go search for a tutorial on PHP+MySQL. If you don't like PHP-ish, you're probably better of finding another solution though :p
Example tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql
You need to store the data you want be retrievable/update-able from multiple clients, to be stored on a server.
You can use any server side language with a database.
Server Languages : PHP, ASP.net, JSP, ColdFusion
Database : MySQL, MSSQL, PostgreSQL, Oracle, DB2 etc..
Use whatever combination you are comfortable with.
In general:
You have a web app that increments the counter in the database
call the page using URLLoader from your AS3 banner.
Database
counter_table
-------------
counter INT
PHP File
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name');
mysql_query('UPDATE counter_table SET counter = counter + 1');
AS3 Banner
// url request with your php page address
var scriptRequest:URLRequest = new URLRequest("http://www.example.com/script.php");
// loader
var scriptLoader:URLLoader = new URLLoader();
// load page to trigger database update
scriptLoader.load(scriptRequest);
Do you also want to retrieve the value of the number of clicks in Banner ?
Easy solution (really not the best :) You should use one of the other answers.. anyways, make a php file that reads txt file containing the count of visits.. and in your flashbanner just call the php file. It'll add one hit per call..
PHP:
<?php
/**
* Create an empty text file called counterlog.txt and
* upload to the same directory as the page you want to
* count hits for.
*
*
* #Flavius Frantz: YOU DONT NEED THESE:
* Add this line of code on your page:
* <?php include "text_file_hit_counter.php"; ?>
*/
// Open the file for reading
$fp = fopen("counterlog.txt", "r");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Display the number of hits
// If you don't want to display it, comment out this line
//echo "<p>Page views:" . $count . "</p>";
// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");
// Write the new count to the file
fwrite($fp, $count);
// Close the file
fclose($fp);
?>
Example code from: (google: php counter file) http://www.totallyphp.co.uk/text-file-hit-counter
Code is not tested, but looks ok. I only commented just a little..

Less painful way to migrate from MySQL to a local single file implementation of the database (flash & AS3)

i have a database in MySQL who i query from a php script. Now i want to run the same aplication but in local (without the php script, the mysql and whitout the server). I develop the IDE of the new app using flash (AS3), now the think is that i need to migrate the data base too.
I was thinking using SQLite wich is great because it use the same commands that mysql and is local, but i really dont know how to make querys from AS3 to sqlite whitout using php. I was also thinking to develop a simple script who read my actual data base (mysql) and parse all the data to a new XML file who then i can read from the new IDE develop in flash, the problem is, that in this way i have to write all the code for the querys, i mean, when i use php+mysql and i need all the data WHERE reef=2 i just make a simple query, but with the new hypothetical schema flash+xml to make a simple query like that i have to write a lot of code if you know what i mean.
So, if you have any ideas let me know, remember that im developing in AS3 with FLASH. Thanks!
adobe air is the only way you can achive this on a local computer.
here some snippets:
// connect to SQLite
var file:File = preferences.resolvePath("data.db");
var sqlConnection:SQLConnection = new SQLConnection();
sqlConnection.open(file);
// prepare statement to find photos in album
var stmtFindPhotosToAlbum:SQLStatement = new SQLStatement();
stmtFindPhotosToAlbum.sqlConnection = sqlConnection;
stmtFindPhotosToAlbum.text = "SELECT * FROM photos WHERE album_id = :album_id";
// execute query
stmtFindPhotosToAlbum.parameters[":album_id"] = 'albumId';
stmtFindPhotosToAlbum.execute();
// get result
var photos:Array = stmtFindPhotosToAlbum.getResult().data;
var photoVos:Array = [];
if (photos != null && photos.length > 0)
{
for(var i:int = 0;i<photos.length;i++)
{
// ...
}
}

AS3 and mySQL or XML: Saving user votes on server from a flash movie

A project of mine involves a flash movie (.swf) in a webpage, where the user has to pick from a number of items, and has the option to thumbs up or thumbs down (vote on) each item.
So far I have gotten this to work during each run of the application, as it is currently loading the data from an XML file - and the data is still static at the moment.
I need to persist these votes on the server using a database (mySQL), such that when the page is reloaded, the votes aren&apos;t forgotten.
Has anyone done this sort of thing before?
The two mains methods that I have found on the &apos;net are
either direct communication between AS3 and the SQL using some sort of framework, or
passing the SQL query to a PHP file, which then executes the SQL query and returns the SQL to AS3.
Which of these methods is the better option?
For the latter method (involving PHP), I have been able to find resources on how to acheive this when attempting to retrieve information from the database (i.e. a read operation), but not when attempting to send information to the database (i.e. a write operation, which is needed when the users vote). How is this done?
Thank you!
Edit: Implemented solution
Somewhere in the PHP file:
if ($action == "vote")
{
$id = $_POST['id'];
$upvotes = $_POST['upvotes'];
$query = "UPDATE `thetable` SET `upvotes` = '$upvotes' WHERE `thetable`.`id` = '$id' LIMIT 1 ;";
$result = mysql_query($query);
}
Somewhere in the ActionsScript:
public function writeToDb(action:String)
{
var loader:URLLoader = new URLLoader();
var postVars:URLVariables = new URLVariables();
var postReq:URLRequest = new URLRequest();
postVars.action = action;
postVars.id = id;
postVars.upvotes = upvotes;
postReq.url = <NAME_OF_PHP_FILE>;
postReq.method = URLRequestMethod.POST;
postReq.data = postVars;
loader.load(postReq);
loader.addEventListener(Event.COMPLETE, onWriteToDbComplete);
}
I am not aware of any framework that supports method-1.
I would use method-2 - but instead of making the query within Flash and passing it to PHP, I would rather pass the related data and construct the query in PHP itself. This is safer because it is less susceptible to SQL injection attacks.
This answer has an example of sending data from flash to the server - it talks about ASP, but the method is same for PHP (or any technology) - just change the URL.
Within the php code, you can read the sent data from the post $_POST (or $_GET) variable.
$something = $_POST["something"]
Many different options:
AMFPHP - binary messaging format between PHP and Actionscript/Flash.
LoadVars - for POSTing and GETing values to a PHP script.
JSON - Using the AS3Corelib you can post JSON formatted data to your web site (just like an AJAX script does).

Categories