Game Development Community

dev|Pro Game Development Curriculum

Web Chat for TGE, Communicate from the Outside

by JuanMa · 05/06/2008 (2:30 pm) · 6 comments

Download Code File

Ok the first thing I want to say is that I did not do all these all by myself, I have to give lots of credits to John Vanderbeck because a big chunk of my torque script code is based on his resource TorqueScript based custom chat client & server. Also I did some modifications to an external resource for the web chat.

Now that I have given credit to these people lets get into action:

On your Game Server:
First download the file, unzip it and place the commandServer.cs file inside commom/server/ folder. Make sure you add the exec("./server/commandServer.cs"); in common/main.sc inside the function initBaseServer().

Now go to common/ server/commands.cs and in the serverCmdTeamMessageSent function at the end add:
function serverCmdMessageSent(%client, %text)
{
   if(strlen(%text) >= $Pref::Server::MaxChatLen)
      %text = getSubStr(%text, 0, $Pref::Server::MaxChatLen);
   chatMessageAll(%client, '\c4%1: %2', %client.name, %text);
   // ADD THESE TWO LINES
   %playerName=strToPlayerName( %client.player.getshapename() ); //<------- add this line!!
   serverLogEvent("CHAT", %text, %playerName);//<------- add this line!!
}

OK, so I think at this point you are done with the torque script modifications.

On your web server:
Go to init.php and type the information to get connected to your database: server, username, password, DBname. At the end of the of this file you will see a method call connectToGameServer look for the call socket_connect and change the IP address to your GAME SERVER IP Address.

Place all the 6 PHP files in a chat folder, you should also have a contents.html and a background.jpg (I do not provide a background image so you have to make your own, this will be cool if you want to match your game theme).

here is the SQL to create the database you will be using to keep track of your messages:

CREATE TABLE Chat_Users (
  UserID int(10) unsigned NOT NULL auto_increment,
  UserName varchar(20) NOT NULL default '',
  LastUpdate timestamp(14) NOT NULL,
  PRIMARY KEY  (UserID)
);
CREATE TABLE
 Chat_Messages (
  MessageID int(10) unsigned NOT NULL auto_increment,
  UserID int(10) unsigned NOT NULL default '0',
  Posted timestamp(14) NOT NULL,
  Message varchar(255) NOT NULL default '',
  PRIMARY KEY  (MessageID)
);

Ok if every thing goes well you should be able to go to your chat login page.

myDomainName.net/chat/login.php

and enter a nickName and then login to the chat.

Just to make sure that the chat is working open another web browser for example IE (considering that your main web browser is firefox) and access the chat with a different nick name. You should be able to chat with yourself, lol.

If this is working fire up your game and enter any level. Open your (server) console command and type

>startComServer();
this will initiate the TCPObject that will be listening for connections from the web chat.

If you are interested only in the chat functionality you can stop reading here. I will give a little more explanation on how to expand this code to send commands to the game server and do stuff from a telnet client of even a web page!!
//----------------------------------------------//

How the protocol works:
The first thing we have to know is how the structure of the external command system:

command;argument

This command and argument is what the game server is going to be waiting for.

Working examples are
LOGIN:
[command]=="login" 
	*[argument]==nickname
	*Register user in user array.
CHAT:
[command] == "chat" 
	* [argument] == message
	* Send message to local chat
COMMAND:
[command] == "command"
	* Execute argument as command
	* List of commands to execute;
 		o [argument]: "getClients" Get number of clients.
 		o [argument]: "webInfo" Get general information about web clients
 		o [argument]: "gameInfo" Get information about game clients 
 		o ...
EVAL:
[command]=="eval"
	* evaluate command as written in the arguments
	* [argument]=="StopServer();"
GOODBYE:
[command]== "goodbye"
	* [argument]== "message"
	* Will print goodbye and disconnect the client from the server.
Let's look at the code to try to figure out how does it work. Open the commandServer.cs and go to the EXTSocket::processLine fuction.

%posSep = strpos(%line, ";");
	if (%posSep <= 0)
		return;
	%len = strlen(%line);
	%command = getSubStr(%line, 0, %posSep);
	%argument = getSubStr(%line, %posSep + 1, %len - %posSep + 1);
The code parses the command and the argument and puts it into the corresponding variables.

// get user details
   %nickname = getClientNickname(%id);
   %i = findClientRecord(%id);
   if (%command $= "logLogin")
      	// send a chat message notifying everyone of the login
	sendToChat("public", "server", "", %argument @ " has signed on from the Web Chat Room.");
		
   // prevent guest to access commands before they have entered a valid nickname   
   if(%nickname $= "Guest" && %command !$= "login" )
      return;
When a connection is established and the processLine function is called, we receive an id that is unique to the client. Every client on connection has been given the name "Guest". The logLogin can be placed in a better place or removed...

switch$ (%command)
	{
 ...
		case "eval":
		   eval(%argument);
		   
      		//************************************ 
		case "command":
		   executeCommand(%argument);
		   
      		//************************************ 
		default:
		   // If the switch gets to here, then we have a bad or unknown command.
		   echo("[" @ %nickname @ ":" @ %id @"] Malformed command, or unrecognized command has been issued");
	}
On this piece of code we are only going to look only at two cases. The first one is "eval" this method will execute any function on the server side of the code. I have placed two functions that do not do anything but are mainly for educational purposes. The first one is printStr().

eval;printStr();
The output on the game server console should be: "Print simple line"

I also have
eval;stopServer();
The output on the game server console should be: "Silly client, you think you can stop the server???"

Now the executeCommand() is a "stub" for now, but you can create a list of things that you could potentially do while in the game. One thing I will be experimenting with very soon will be to remove users that are using inappropriate language or change the particle effects on the fly.

By now you should probably get the idea that this exec command could be quite flexible if you know what you are doing.

Testing the Application using stopServer and printStr:
But let's test these two methods. Start your game (there is no need to start a mission) and type on the command line
// a port number can be passed as an argument, the default one is 20020
startComServer();

If you are working in windows go to run and type cmd then telnet
From your telnet session type
//o game.server.address portNumber. The default port number is 20020
o localhost 20020
And press enter. At this point you should see a message on you game server console IP:127.0.0.1:XXXX got Connected
On you telnet type the following commands
login;myUserName
eval;printStr();		
eval;stopServer();
command;something
These is what you should see on your console the output
==>startcomserver();
Binding server port to default IP
listening for new connection in port: 20020
IP:127.0.0.1:XXXX got Connected
***Recieved "login;myUserName"


***Recieved "eval;printStr();"


Print simple line
***Recieved "eval;stopServer();"


Silly client, you think you can stop the server???
***Recieved "command;something"

executeCommand Stub!!
//----------------------------------------------//

NOTES ON THE PHP CODE:
If you decide to use the php code for the chat and expand it, keep in mind that every time you run a page that connects to the game server it will open a connection, do what it is supposed to do (usually log in and one command execution) and then close the connection. If you want to execute more than one command per connection, the connectToGameServer function inside init.php supports this. If you send a username, and empty string as the command and an argument constructed as follows:

"command1;argument1\ncommand2;argument2\n..."

The game server will execute it all.

NOTES ON ServerLogEvent
We are currently using a modified version of this method to keep track of user behavior and also to check from our website if the servers are up or down. To do this we create a query just like the one on the code and send it to a php file that will parse it and insert the information in the correct tables. Currently the HTTPObject can only send one argument that is the reason why we hide it inside q. the php code breaks down the string inside gamechat.php like this
// get and break all the arguments sent by the game server
    $qget = $_GET['q'];
    $data = array();
    $data = explode("&", $qget);
    foreach($data as $key=> $value)
    {
        $temp = explode("=", $value);
        $data[$temp[0]] = $temp[1];
    }
    $name = $data['NAME'];
    $player = $data['PLAYER']."\[IG\]"; // add identifier In Game
    $event = $data['EVENT'];

I do not know if this resource will match the expectations of the people that commented on this page already, but I do hope that this could be useful to some to create some cool game-outsideWorld interaction!!

Juanma

UPDATE:
I clean up the files a bit.

About the author


#1
05/06/2008 (4:14 pm)
Control my game server via my forums and a TCP object?!
Epic theory, I would like to hear more!
#2
05/06/2008 (4:56 pm)
i too want to hear more. very interesting work.
#3
07/20/2008 (11:17 am)
Very big interesting work!..

With little modification can change it in one lobby system for team play..

i Think..
#4
02/01/2010 (11:49 pm)
Hi, great resource by the way.

I do have a question tho. I got this working with TGEA 1.8.2 except for when you chat in the php side of things it does not show up in TGEA.

Chat msg so up from torque to web site but not the other way around.

Any ideas?

Thanks
#5
02/02/2010 (2:06 pm)
NVM, I had forgotten to set the game ip in the init.php file. DOH
#6
07/14/2010 (3:57 pm)
I lost all my backup files and had to start over from scratch.
I am using TGEA 1.8.1 and xampp server for testing.

I have database setup and I can login and type a chat msg but nothing shows up in the chat box but I can look in the datbase and chat_messages and chat_users both have the data I just entered.

Also none of this shows up in my game.
Any Info?

Thanks