PDA

View Full Version : Web Live



cairnswm
14-03-2004, 01:17 PM
Web Live

Many games have a need to store information on a live web page. This could range from High Scores information all the way to Online Registration Checking. It is even possible that programs could make a persistent world through sharing information through an online web store.

Other possible applications for a program that is aware of the internet is to store information on the internet and let the programs share this information from a central point, this information could be in the form of data from a database, a news feed or regular updates to issues in a project.

Web Services

A web service is:
a piece of code that delivers some information through a call to the internet Using this simplified definition it is possible to think of even an HTML page as a web service. Or more important for this tutorial any ASP or PHP page on the internet is a web service.

Web services have a complex and rather pointless set of protocols that have to be adheered to. Using the above web service definition it is clear that web services can be significantly simplified and yet still deliver on their promises. This tutorial is going to show you a very simple method for turning your Delphi programs into Web Live applications.

The Web Service

For my example I'll be using ASP to create a very simple web service. The web service will simply do the game of Hi-Lo.
The game will have two services:
1. Check Game Status
2. Allow a guess on an existing game or start a new game if no game is in progress.
These two services could be done as a single ASP file but for simplification I'll split them into two services.


<%
' Web Service "GameState"
'
' Load Game State info
' Valid values are
' No Game
' Game in Progress

GameState = Application&#40;"GameState"&#41;

' Check if first time being run
If Len&#40;GameState&#41; < 1 then
GameState = "No Game"
Application&#40;"GameState"&#41; = GameState
End If

' Based on GameState return Game Status
Response.Write GameState

'End Web Service "GameState"
%>


If you load this onto your local web server and load the page you'll see that it says "No Game". To start a game we'll need a second web service that accepts the input from a form and replies based on the game information.

In this next piece of code I have left all the debug statements in the code as the server expiry on code pages makes it difficult to see exactly what it does correctly. To get this working correctly you really need to store the information in a database and build the response from the database.



<%
' Web Service "Game"
'
' Accepts the input from a form
' The form needs to inputs, input one is a UserName box
' input two is a Guess box
' If no game in progress then starts a new game
' If game is in progress will then reply if guess is higher/lower
' than the right answer

GameState = Application&#40;"GameState"&#41;

' Check if first time being run
If Len&#40;GameState&#41; < 1 then
'Response.write "No GameState info available <BR>"
GameState = "No Game"
Application&#40;"GameState"&#41; = GameState
End If

'Response.write GameState & "<BR>"

' If No Game in Progress then Start a game
If GameState = "Game in Progress" then
RandomNumber = cint&#40;Application&#40;"Number"&#41;&#41;
Else
GameState = "Game in Progress"
'Response.write "New game started<P>"
RandomNumber = &#40;Second&#40;Now&#41;+Minute&#40;Now&#41;&#41; mod 100
Application&#40;"Number"&#41; = cstr&#40;RandomNumber&#41;
End If

Guess = cint&#40;Request.QueryString&#40;"Guess"&#41;&#41;
If Guess = RandomNumber then
Response.Write "You Guessed " & RandomNumber & " right!"
GameState = "No Game"
Else
If Guess < RandomNumber then
Response.Write "Your Guess of " & Guess & " is lower than " & RandomNumber
GameState = "Game in Progress"
Else
' Guess > Random Number
Response.Write "Your Guess of " & Guess & " is higher than " & RandomNumber
GameState = "Game in Progress"
End If
End If

Application&#40;"GameState"&#41; = GameState

'End Web Service "Game"
' Issues - if two people playing the one person will never know if the
' game is done and will effectivly restart the game
' Solve this by adding a third input for game number.
%>


Delphi Calls

All the web services we require are now set up and ready to go. Now we need to look at the Delphi side of things to communicate with the web services. Obviously the web services are accessed through an HTTP call (the standard web protocol) and we need to make delphi call the web services using the same protocol. Fortunatly Delphi has a number of HTTP components available to make this process very easy. I have read of a number of problems being experienced using the FastNet HTTP component (TNMHTTP) so I use the Indy HTTP component (TidHTTP) for my programs.

1. Create a form
2. Add a idHTTP component
3. Create function


procedure TForm1.HTTPGet(Addr: String; var Data: String);
begin
Data := idHTTP1.Get(Addr);
end;


Simple huh!

Basically this function sends a call to the server (you define the address) and returns whatever output it gets through the Data string. To be able to make guesses etc we need to add the guess being made (http://webadr/Game.asp?Guess=XYZ).

So I created a form with an EditBox (eGuess) for the player to enter their guess, a Button (btnGuess) to push to send the request to the Web Service, a label to show the result and a memo box to display error information. All this is of course debug level code and should be cleaned up a whole lot :).

The on the button press I added :

procedure TForm1.btnGuessClick(Sender: TObject);
Var
S : String;
begin
Try
HTTPGet('http://cairnswmnb/HiLo\game.asp?guess='+eGuess.Text, S);
If Pos('ight',S) > 0 then
Label1.Caption := 'RIGHT'
Else If Pos('high',S) > 0 then
Label1.Caption := 'Too High'
Else If Pos('low',S) > 0 then
Label1.Caption := 'To Low'
Else
Memo1.Text := S;
Except
On Exception do
Begin
Memo1.Text := S;
End;
End;
end;


When the program is run, the player enters a value in the enit box and presses Guess. The guess is actually processed at the server side and not by the Client PC.

So what now

This program architecture is relativly easy to implement and can be used for many many different solutions. An online quiz program, an online game server are just two very simple uses for this system. I am currently using this method in a project at work to load information from a central database without the requirement of building a link to the database from each PC. As this method works using the HTTP protocol it will be able to be passed through most firewalls thereby making it a great way to get your own personal information on your web site accessable from anywhere.

In addition it is possible to make a Delphi program post information to online forms using a similar method. Each field of the input form and its related value are stored in input=value format in the FormInfo string list.

procedure TForm1.PostForm(Addr: String; FormInfo: TStringList;
var Data: String);
var
aStream: TMemoryStream;
Params: TStringStream;
SL : TStringList;
I : Integer;
S : String;
begin
aStream := TMemoryStream.create;
Params := TStringStream.create('');

try
with IdHTTP1 do
begin
For I := 0 to FormInfo.Count -1 do
Begin
S := FormInfo[I];
If I < FormInfo.Count-1 then
S := S + '&';
Params.WriteString(URLEncode(S));
End;
Request.ContentType := 'application/x-www-form-urlencoded';
try
Post(Addr, Params, aStream);
except
on E: Exception do
showmessage('Error encountered during POST: ' + E.Message);
end;
end;
aStream.WriteBuffer(#0' ', 1);
aStream.Position := 0;
SL := TStringList.Create;
SL.LoadFromStream(aStream);
Data := SL.Text;
SL.Free;
except
end;
end;

Traveler
14-03-2004, 08:33 PM
Wow!! Very interesting material here :shock:
I'm definitely going to check this out real soon!!

Nice work cairnswm!

cairnswm
15-03-2004, 05:19 AM
Cool, let me know what you use it for. At the moment I'm only using it for XML calls to my server - creating a single point of DB access.