Friday 7 January 2011

SFS1X: Database Login

Hi there! In this tutorial I'll explain how can you make a simple Flash Application that connects and then logs in, after the server verifies the credentials to check if there is a user registered with those credentials. This tutorial will be based in the Simple Login Tutorial, so I suggest you to do it before doing this.

For making the Database Login, I'll use:
- H2 Database as the database that will store the registered user's information;
- An AS1.0 Extension, that will handle the login process;

You can download the source code of this tutorial here.

So, the Client Side

First open the Fla file that you created in the Simple Login Tutorial.
You'll need to create a new Input TextField after the userName (using the Text Tool, shortcut key: Tand give it the Instance Name "passWord" without the quotes and set its Behavior property to Password (Like the following image).


You can optionally add a new Dynamic TextField after the userName and give it the Instance Name "errorMsg" without the quotes. This TextField will show the common login errors like "Username or password wrong", "can't connect to the database", etc.

Finally you need to edit some of the code that is in the first frame, so it will stay like this:
import it.gotoandplay.smartfoxserver.*;
stop();

var ip:String = "127.0.0.1";
var port:Number = 9339;
var zone:String = "TutorZone";
var connected:Boolean = false;

userName._visible = false;
passWord._visible = false;
login_btn._visible = false;

var smartfox:SmartFoxClient = new SmartFoxClient();
smartfox.debug = true;
connect();

function connect() {
 status.text = "Connecting";
 smartfox.connect(ip,port);
}

smartfox.onConnection = function(success) {
 if (success) {
  status.text = "Successfully connected!";
  connected = true;
  userName._visible = true;
  passWord._visible = true;
  login_btn._visible = true;
  login_btn.onRelease = sendLogin;
  Selection.setFocus(userName);
 } else {
  status.text = "Can't connect!";
 }
};

function sendLogin() {
 if (connected) {
  if (userName.text != "") {
   error.text = "";
   status.text = "Logging in...";
   smartfox.login(zone,userName.text,passWord.text);
  }
 }else{
  connect()
 }
}

smartfox.onExtensionResponse = function(resObj:Object) {
 if (resObj._cmd == "logOK") {
  _global.myName = resObj.name;
  smartfox.getRoomList();
 } else if (resObj._cmd == "logKO") {
  error.text = "Error at login: "+resObj.error;
  status.text = "Connected";
 }
};

smartfox.onRoomListUpdate = function(roomList:Object) {
 gotoAndStop("lobby");
 display.text = "Logged in as "+_global.myName;
};

smartfox.onConnectionLost = function() {
 gotoAndStop("Login");
 status.text = "Disconnected";
 connected = false;
 userName._visible = false;
 passWord._visible = false;
};
As you can see, I changed the Zone to TutorZone, added some lines to make the passWord TextField disappearing at the beggining and appearing when it successfully connects, like the userName.


Important Warning: I decided to change the Zone not to interfere with the zones that already come with sfs and that are needed for the examples, and from now I'll be always using the TutorZone in the next tutorials.


So you'll need to create a new Zone. If you don't know how to create a new Zone, you can follow the Basic Server Configuration Tutorial.


But there is one important change that I did to the script. The new connect function and the Extension Response, Connection Lost  and RoomList Update handlers.


So let's explain this code:

function connect() {
 status.text = "Connecting";
 smartfox.connect(ip,port);
}

I only created this function so this way I can connect to the server just by executing connect() (or _root.connect() if the code is inside a movieclip) and i dont need to be always displaying the status and calling the smartfox.connect(ip, port). I've also created a connected Boolean, that is true when the client is connected to the server and is false when the client isn't.
In the sendLogin function, now it verifies if it is connected to the server, and if it isn't, it tries to connect to the server again.
smartfox.onExtensionResponse = function(resObj:Object) {
 if (resObj._cmd == "logOK") {
  _global.myName = resObj.name;
  smartfox.getRoomList();
 } else if (resObj._cmd == "logKO") {
  error.text = "Error at login: "+resObj.error;
  status.text = "Connected";
 }
};
This function handles the onExtensionResponse event fired by the client when it receives a response from the Extension. I'll talk more about the extension in the Server Side part of this tutorial. The resObj returns the data from the server. In this tutorial the Extension will return the command "logOK" if the login succeeded or will return the command "logKO" if the login failed.
If the login succeeded, I set a global variable called myName that will represent our public name (the name that everyone sees). Then it executes the getRoomList() command. This command is only used if the customLogin parameter in the Zone is set to true. If it is true, it tells the server that "you don't need to handle the login, because I have an extension that will handle it for you". When handling the customLogin, you need to manually request the roomList from the server, otherwise you won't be able to join any room. But if you don't have the customLogin set to true, in other words you aren't handling the login with an extension, you don't need to request the roomList, because the server automatically sends it after the login.
If the login failed, it displays the error sent by the extension in the error TextField and displays again the "Connected" in the status TextField.
For more information about the onExtensionResponse you can check the docs (http://www.smartfoxserver.com/docs/index.htm?http://www.smartfoxserver.com/docs/docPages/tutorials_pro/02_simpleExtension/index.htm) and the API (http://www.smartfoxserver.com/docs/docPages/as2/html/it_gotoandplay_smartfoxserver_SmartFoxClient.html#onExtensionResponse).
smartfox.onRoomListUpdate = function(roomList:Object) {
 gotoAndStop("lobby");
 display.text = "Logged in as "+_global.myName;
};
This function handles the onRoomListUpdate event by the client when it receives the roomList from the server. In further tutorials I'll use the received roomList, but for now I don't need it. When it receives the roomList, it just goes to the lobby frame and displays message "Logged in as Rjgtav" for example, in the display TextField.
smartfox.onConnectionLost = function() {
 gotoAndStop("login");
 status.text = "Disconnected";
 connected = false;
 userName._visible = false;
 passWord._visible = false;
};
This function handles the onConnectionLost event fired when the client loses the connection with the server. When it loses the connection, it goes to the login frame (in case it is in the lobby frame), shows the "Disconnected" in the status TextField, sets the connected variable to false and hides the userName and passWord TextFields.

We're done with the Client Side, now to the Server Side.
First you'll need to have a database. If you don't have one, you can create one by simply doing this:

1. Open the adminDb.bat in the [SmartFoxServer Installation Folder]\Server (for Windows users) or run ./adminDb.sh command in a terminal window (it will open a new browser window with the h2 login page - at least in Windows it opens).
2. Now enter "jdbc:h2:~/sfstutor" without the quotes as the JDBC URL and enter your desired User Name and Password.
3. Finally press the Connect button.


Now that you have a database, you need to create a table. For that, you just need to run this SQL Statement (you can run SQL statements by entering them in the big central TextField and by clicking the Run (Ctrl+Enter) button):

CREATE TABLE USERS(ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(255), PASS VARCHAR(255), EMAIL VARCHAR(255));

I'll explain this code very quick:

CREATE TABLE USERS() - Creates a new table called USERS and its collums. The collums are set inside the parentheses ();
ID INT AUTO_INCREMENT PRIMARY KEY - A collum called ID and type INT. The AUTO_INCREMENT will make the collum values automatically increase by 1 (like 1, 2, 3, blabla). It is the primary key of the table (you can only have one primary key per table);
NAME VARCHAR(255) - A collum called NAME and type VARCHAR with a maximum of 255 characters; 
PASS VARCHAR(255) - A collum called PASS and type VARCHAR with a maximum of 255 characters;
EMAIL VARCHAR(255) - A collum called EMAIL and type VARCHAR with a maximum of 255 characters;

Now that you have a table, you only need to do one more thing. You need to insert data, in other words register users, for now, I'll only explain how to do it by a SQL Statement. I'll explain how to make a register in a future tutorial. For registering the first users, you only need to run this SQL Statement:

INSERT INTO USERS (NAME, PASS, EMAIL) VALUES ('User's Username', 'User's Password', 'User's Email');

A quick explanation:

INSERT INTO USERS() - Inserts data into the table USERS. The collum's names that we are going to insert data are set inside the first parentheses () and the data to be inserted is set inside the last parentheses ();

Note: The data position inside the last parentheses must match the correspondent collum's position in the first parentheses.

And you're done with the database. Now the extension.

You need to create a new Extension called DatabaseLoginExt. If you don't know how to create an extension, you can check the Simple Extension Tutorial.

This is the source code of the Extension:

var dbase
var userName;
var passWord;
var SocketChannel;

function init(){
 dbase = _server.getDatabaseManager()
}

function destroy(){
 delete dbase
 delete userName;
 delete passWord;
 delete SocketChannel;
}

function handleInternalEvent(evt)
{
 if(evt.name == "loginRequest"){  
  var error = "";
  
  userName = evt["nick"];
        passWord = evt["pass"];
        SocketChannel = evt["chan"];
  
  var sql = "SELECT COUNT (NAME) FROM USERS WHERE NAME='"+userName+"' AND PASS='"+passWord+"'";
  var queryRes = dbase.executeQuery(sql)
  
  var response = {}
  
  if (queryRes != null){
   var Row = queryRes.get(0)
   var count = Row.getItem("COUNT(NAME)");
    
   if(count == 1){
    trace("SUCCESSFULL LOGIN")
    var obj = _server.loginUser(userName, passWord, SocketChannel)
    
    if(obj.success){
     response._cmd = "logOK";
     response.name = userName;
    }else{
     error = obj.error;
     response._cmd = "logKO";
    }
   }else if(count == 0){
    trace("FAILED LOGIN")
    response._cmd = "logKO";
    error = "Wrong username or password";
   }
  }else{
   response._cmd = "logKO";
   error = "Error connecting to the database"
  }
  
  response.error = error;
  _server.sendResponse(response, -1, null, SocketChannel)
 }
}

Here's the explanation of the Extension code:

function init(){
 dbase = _server.getDatabaseManager()
}
This function handles the init event. When the Extension inits, it sets the dbase variable as the Zone's Database Manager.
function destroy(){
 delete dbase
 delete userName;
 delete passWord;
 delete SocketChannel;
}
This function handles the destroy event. When the Extension is destroyed, it deletes all the used variables.
if(evt.name == "loginRequest"){
Checks if the event received is the loginRequest (the one that is sent when the client is requesting to login).
userName = evt["nick"];
passWord = evt["pass"];
SocketChannel = evt["chan"];
The evt param received from the loginRequest event, is an Object. So we are setting the variables to the correspondent data in the evt Object.
Note: It could be evt.nick instead of evt["nick"]. It's the same
var sql = "SELECT COUNT (NAME) FROM USERS WHERE NAME='"+userName+"' AND PASS='"+passWord+"'";
This code sets the sql variable. It is a prepared statement. This prepared statement counts the number of users in the database that have the received userName and passWord.
var queryRes = dbase.executeQuery(sql)
This code makes the Database Manager execute the Prepared Statement sql and sets the queryRes variable as the result returned from the query. There are two commands to execute a SQL Statement. The executeQuery() and the executeUpdate(). The difference between them is that the executeQuery() only queries the database, in other words, gets data from it and the executeUpdate() only updates the database, for example, insert new data.
var response = {}
Creates a new Object. The response Object will be sent to the client (ExtensionResponse event).
var Row = queryRes.get(0)
var count = Row.getItem("COUNT(NAME)");
The queryRes object is the result returned from the query and the result is made of rows. As the database won't have duplicated users, the result will only return a maximum of one row, and as the queryRes is an Array, we get its first parameter (the 0). The Row has items (corresponding to the collums), and when we do a SELECT COUNT(), it only returns a collum called COUNT(the name of the collum to count). So we get that item and assign it to the count variable.
var obj = _server.loginUser(userName, passWord, SocketChannel)

if(obj.success){
 response._cmd = "logOK";
 response.name = userName;
}else{
 error = obj.error;
 response._cmd = "logKO";
}
If the count equals 1, than that means that there's a registered user with the entered credentials, so we login it and assign a variable to the loginUser function, that will be the return of the function. If it returns true, it means that the user successfully logged in. If it returns false, it means that it failed during the log in proccess. Then we set the _cmd of the response. This property is like the name of the result from the ExtensionRequest sent by the client. In this case, we set it as "logOK" if the login succeeded and "logKO" if the login failed. And if the login failed, we assign the error to a variable, that will be returned inside the response Object.
response.error = error;
_server.sendResponse(response, -1, null, SocketChannel)
In this code we set the error property inside the response Object as the error (As you can see along the code I set some more errors). Then we send the response back to the client. For more information about the sendResponse() function you can check the ServerSide API (http://www.smartfoxserver.com/docs/docPages/serverSideApi/_server/sendResponse.htm)

Now, all you need to do is to modify your Zone in the config.xml, so it will stay like this:


<Zone name="TutorZone" uCountUpdate="true" maxUsers="10000" customLogin="true" roomListVars="true">
        <AutoReloadExtensions>true</AutoReloadExtensions>
        <Rooms>
                <Room name="Login" maxUsers="5000" autoJoin="true" limbo="true" />
                <Room name="Lobby" maxUsers="5000" isPrivate="false" isTemp="false" autoJoin="false" uCountUpdate="true" extensionName=""/>
        </Rooms>
        <DatabaseManager active="true">
                <Driver>sun.jdbc.odbc.JdbcOdbcDriver</Driver>
                <ConnectionString>jdbc:h2:~/sfstutor</ConnectionString>
                <UserName>Your database's UserName</UserName>
                <Password>Your Database's Password</Password>
                <TestSQL><![CDATA[SELECT COUNT(*) FROM USERS]]></TestSQL>
                <MaxActive>100</MaxActive>
                <MaxIdle>100</MaxIdle>
                <OnExhaustedPool>fail</OnExhaustedPool>
                <BlockTime>5000</BlockTime> 
        </DatabaseManager>
        <Extensions>
<extension name="LoginExt"  className="DatabaseLoginExt.as" type="script" />
</Extensions>
</Zone>


For more information about how to create a Zone you can check the Basic Server Configuration Tutorial.

Tip: Don't forget to set the Local playback security to Access network only. For more information about this, you can check this tip.


You can download the source code of this tutorial here.


And that's all. I hope you enjoyed this tutorial. If you have any questions, fell free to ask me (by commenting or by dropping me a pm in the sfs forums).

Stay tuned for the next tutorial ;-)

SFS1X: Simple Extension

Hi. In this tutorial I'll explain how to make the most Simple Extension, most known as "Hello World" Extension.

Importat Note: This is a Zone Level Extension, so it's attached to a Zone. There are the Room Level Extensions too, but the only difference is that they're attached to a Room instead.

An Extension, as the name says, is a way to extend the server functionalities. It has many uses like handling the Login proccess (by verifying the credentials in a database), handling a game (like the score of each player in the game) and any other things.

So let's begin the tutorial!

First you need to create a new ActionScript File. Then you only need to put there this code:
function init()
{
 trace("Hello World!")
}

function destroy(){
 trace("Bye World!")
}

function handleRequest(cmd, params, user, fromRoom){
 trace("Request Received from: "+user.getName())
}

function handleInternalEvent(evt){
 trace("Event received: "+evt.name)
}
As you can see, the Extension has only this functions (plus the handleRequest function) to handle the server events. 

The init function handles the init event that is fired when the extension is inited (after the Zone is inited). In this case, we only display the "Hello World!" message, that can be checked in the console, after the correspondent Zone is inited.

The destroy function handles the destroy event that is fired when the extension is destroyed. In this case, we only display the "Bye World!" message, that can be checked in the console.

The handleInternalEvent function handles all the internal events that are fired, like userJoin, userExit, etc. In this case we only display the name of the event received. 

The handleRequest function handles the request event sent by the client (with the sendXtMessage). 

Now you only need to deploy the Extension. To do that, you need to copy you ActionScript File to the [SmartFoxServer Installation Folder]\Server\sfsExtensions folder, then you need to add your Extension to the Zone where you want to place it. For that you need to enter the following code, in the <Extensions> block that is in your Zone block. So it will stay like this:

<Zone name="Your Zone" blablablabla>
        bla
        bla
        bla
        <Extensions>
                <extension name="MostSimpleExtension"  className="MostSimpleExtension.as" type="script" />
        </Extensions>
</Zone>

The extension configuration has the following parameters:

name - Is a name that will be used to refer to the Extension. Used in the sendXtMessage(extensionName, blablabla)
className - Is the name of the ActionScript File of the Extension.
type - Is the type of the extension. As it is an ActionScript extension, its type is script. If it was a Java Extension, its type would be java.

After this, you only need to start your Server.

And that's all. I hope you enjoyed this tutorial. If you have any questions, fell free to ask me (by commenting or by dropping me a pm in the sfs forums).

SFS1X: Basic Server Configuration

Hi. This tutorial isn't finished yet. I'll update it as I need in my future tutorials. So let's begin!

Zone

A Zone is like an application (like a game, a chat, etc.) or a group of rooms, if you prefer, and each room has its players that can join all the rooms inside the zone where they are. You can create a new Zone only by editing the config.xml under [SmartFoxServer Installation Folder]\Server (with any text editor like notepad)

To create a new zone, you only need to add this code before the <Zones> section. (Each zone is defined by a <Zone> block)

<Zone name="ZoneName" uCountUpdate="true" maxUsers="200" customLogin="false">
</Zone>

This is a simple Zone. Of course there are much more parameters to set in the Zone like for example roomListVars, that sets if the rooms can have or not Room Variables. Here's an explanation about the above parameters:

name - is the name of the Zone
uCountUpdate - if set to true, it sends to the clients an userCountUpdate event when the number of players/users in a room changes.
maxUsers - sets the maximum amount of users that the Zone will handle
customLogin - if set to false, the server handles the login proccess, but if set to true, the server doesn't handle the login process. When it receives the login request from the client, it redirects it for the Zone Extension, that will handle the login proccess.

This is just the first part of the configuration of a Zone. You need also to configure the default Rooms that will be always in the Zone and there are many other things to configure like the buddyList (optional), the Database Manager (optional), the Extensions (optional), Moderators (optional), etc.

Database Manager

To configure the Database Manager, you need to add this code in the Zone where you want to add it.

<DatabaseManager active="true">
  <Driver>The Driver</Driver>
    <ConnectionString>The URL</ConnectionString>
  <UserName>Database Username</UserName>
  <Password>Database Password</Password>
  <TestSQL><![CDATA[Test SQL Statement]]></TestSQL>
  <MaxActive>100</MaxActive>
  <MaxIdle>100</MaxIdle>
  <OnExhaustedPool>fail</OnExhaustedPool>
  <BlockTime>5000</BlockTime> 
</DatabaseManager>

I think I don't need to explain the paremeters of the Database Manager, as its names tell everything.

I'll explain the of this parameters later.

For more information about the Basic Configuration, you can check the docs (http://www.smartfoxserver.com/docs/index.htm?http://www.smartfoxserver.com/docs/docPages/config/basics.htm)

Stay tuned for updates ;-)

Tuesday 4 January 2011

TIP: Adobe Flash Player Security Error

Hi. When you're developing your Flash applications, sometimes you will need to open the swf file of your app, and you may enounter this warning:




If you get this warning, your swf file will not connect to your server or to the url you're trying to connect.
To prevent this, you only need to set the Local playback security in the Publish Settings (File > Publish Settings..., shortcut key: Ctrl+Shift+F12) to Access network only (Like the following image).


Monday 3 January 2011

SFS1X: Simple Login

Hello readers! In this tutorial I'll explain how to make a simple Flash application that connects and then logs in the server. I'll explain how to make a Database Login in the next tutorial.


You can download the source code of this tutorial here.


So, let's begin!


First open your Flash and create a new Input TextField (using the Text Tool, shortcut key: T) and give it the Instance Name "userName" without the quotes and set its Behavior property to Single line (Like the following image).




You can also select the Show border around text button () in the TextField. This way it will show a black border around it.


Then you need to create a button. For that you first draw your button, then you convert it to a Button Symbol (Right-click in the button, select "Convert to Symbol...") and give it the Instance Name "login_btn" without the quotes (Like the following image).







If you want, you can add the status Dynamic TextField to show the connection status.
Finally add a new KeyFrame and give it the label "lobby" and add give to the first frame the label "login", so it looks like this:




In the Lobby I only put a Dynamic TextField with the Instance Name "display" without the quotes.
After this, you only need to add this code in the first frame:

import it.gotoandplay.smartfoxserver.*
stop();

var ip:String = "127.0.0.1";
var port:Number = 9339;
var zone:String = "simpleChat";

status.text = "Connecting..."

userName._visible = false;
login_btn._visible = false;

var smartfox:SmartFoxClient = new SmartFoxClient()
smartfox.debug = true
smartfox.connect(ip, port)

smartfox.onConnection = function (success)
{
 if (success)
 {
  status.text = "Successfully connected!"
  userName._visible = true;
  login_btn._visible = true;
  login_btn.onRelease = sendLogin;
  Selection.setFocus(userName);
 }
 else
 {
  status.text = "Can't connect!"
 }
}

smartfox.onLogin = function(resObj:Object)
{
 if (resObj.success)
 {
  gotoAndStop("lobby");
  display.text = "Logged in as "+resObj.name;
 }
 else
 {
  status.text = "Error";
  trace("Error Message: "+resObj.error);
 }
}

function sendLogin(){
 if(userName.text != ""){
  status.text = "Logging in..."
  smartfox.login(zone, userName.text)
 }
}

As part of the code is from the Simple Connect Tutorial, I'll only explain the new code.
So here's the explanation:

userName._visible = false;
login_btn._visible = false;

This simple lines of code just hide the userName TextField and the login button to prevent the user from trying to login before being connected. That's why you find this code:

userName._visible = true;
login_btn._visible = true;

When it successfully connects, to show the userName TextField and the login button again to let the user login.

login_btn.onRelease = sendLogin;

This line of code is the same as putting this code in the button:

on(release){
 _root.sendLogin();
}

It calls/executes the function when the login button is clicked.

Selection.setFocus(userName);

What this line of code does is selecting the userName TextField, to facilitate the login to the user. This way the user only needs to write his/her username. For unknown reasons this code only works if you open the swf file or if you open it on the browser.

function sendLogin(){
 if(userName.text != ""){
  status.text = "Logging in..."
  smartfox.login(zone, userName.text)
 }
}

This function first verifies if the userName TextField is empty, and if it isn't, it sends the login request to the server. For further details about the login you can check the docs (http://www.smartfoxserver.com/docs/docPages/tutorials_basic/02_simpleChat_p1/index.htm) and the AS2.0 API (http://www.smartfoxserver.com/docs/docPages/as2/html/it_gotoandplay_smartfoxserver_SmartFoxClient.html#login).

smartfox.onLogin = function(resObj:Object)
{
 if (resObj.success)
 {
  gotoAndStop("lobby");
  display.text = "Logged in as "+resObj.name;
 }
 else
 {
  status.text = "Error";
  trace("Error Message: "+resObj.error);
 }
}

This function handles the onLogin event, that is fired when the login successes or fails. The resObj is an object that returns when that function is called. 
This object has the following variables/properties:
- success Boolean that returns true when the login successes and returns false when the login fails.
- name String that is the public name that everyone sees.
- error String that returns an error message if the login failed.


For more information about the resObj and the login process you can check the AS2.0 API docs (http://www.smartfoxserver.com/docs/docPages/as2/html/it_gotoandplay_smartfoxserver_SmartFoxClient.html#onLogin)


Tip: Don't forget to set the Local playback security to Access network only. For more information about this, you can check this tip.



You can download the source code of this tutorial here.

And that's all. I hope you enjoyed this tutorial. If you have any questions, fell free to ask me (by commenting or by dropping me a pm in the sfs forums).

Stay tuned for the next tutorial (Database Login) ;-)

BLOG: Request a Tutorial

Hi. From now you can request a tutorial by just commenting in the Request a Tutorial page. I hope I can find a better solution for that, but for now it works. Hope you enjoy my bog ;-)

Request a Tutorial

Sunday 2 January 2011

SFS1X: Simple Connect

Hello again. In this tutorial I'll explain how to make a simple Flash application that connects to your server.


You can download the source code of this tutorial here.


First open your Flash and create a new Flash File (ActionScript 2.0).
Create a new Dynamic TextField (using the Text Tool, shortcut key: T) and give it the instance name "status" without the quotes. (Like the following image)


Now the code. Add this simple code to the first frame:

import it.gotoandplay.smartfoxserver.*
stop();

var ip:String = "127.0.0.1";
var port:Number = 9339;
var zone:String = "simpleChat";

status.text = "Connecting..."

var smartfox:SmartFoxClient = new SmartFoxClient()
smartfox.debug = true
smartfox.connect(ip, port)

smartfox.onConnection = function (success)
{
 if (success)
 {
  status.text = "Successfully connected!"
 }
 else
 {
  status.text = "Can't connect!"
 }
}

Here's the explanation of the code:

import it.gotoandplay.smartfoxserver.*

This line imports the SmartFoxClient class.

stop();

This line stops the animation.

var ip:String = "127.0.0.1";

This line sets the variable ip. This variable represents the ip of the machine where the sfs is running, that the Flash application will connect. If the sfs is running in your pc, you can let the ip as 127.0.0.1, but if the sfs isn't running in your pc or you want to publish the Flash application on the web, you need to set the ip as your external ip (the one given from http://www.whatismyip.com/)

var port:Number = 9339;

This line sets the variable port. This variable represents the port where sfs is running (the one configured in the config.xml between the and )

var zone:String = "simpleChat";

This line sets the variable zone. This variable represents the name of the Zone you want to connect. For further explanation about what is a Zone, please check the sfs docs (http://www.smartfoxserver.com/docs/docPages/config/basics.htm#zone)

status.text = "Connecting..."

This line tells the status textField to show the text "Connecting..."

var smartfox:SmartFoxClient = new SmartFoxClient()

This line creates a new instance of the SmartFoxClient object.

smartfox.debug = true

This line sets smartfox's debug flag to true. This way smartfox will output everything that it sends to the server and receives from it. Very useful when developing as it helps solving bugs.

smartfox.connect(ip, port)

This line is the most important in this example. It is the one that makes the SmartFoxClient connect to the previously set ip and port.

smartfox.onConnection = function (success)
{
 if (success)
 {
  status.text = "Successfully connected!"
 }
 else
 {
  status.text = "Can't connect!"
 }
}

This function handles the onConnection event. The onConnection event is fired when it successfully connected or when the connection timed out. It returns a boolean (success) that is true when it successfully connected and is false when it failed connect. When it successfully connects, the status textField shows "Successfully connected" but when it can't connect, it shows "Can't connect".

Tip: Don't forget to set the Local playback security to Access network only. For more information about this, you can check this tip.


You can download the source code of this tutorial here.


And that's all. I hope you enjoyed this tutorial. If you have any questions, fell free to ask me (by commenting or by dropping me a pm in the sfs forums).


Stay tuned for the  next tutorial ;-)

SFS1X: Installing the API

Hi. In this tutorial I'll teach you how do you install the API so that you can develop applications that use sfs.
There are 2 ways to do this. The docs way and the Rjgtav's way.


First I'll explain the docs way, that is better explained in the docs (http://www.smartfoxserver.com/docs/docPages/api/installing.htm)


All you need to do is to point the classpath of your application to the location of the api of the actionscript version you're using.
For example if you're using AS2.0 you need to point it to [SmartFoxServer Installation Folder]\Flash API\Actionscript 2.0
while if you're using AS3.0 you need to point it to [SmartFoxServer Installation Folder]\Flash API\Actionscript 3.0.


To set the classpath of your project all you need to do is click in the "Settings..." button in Properties panel, then click in the  "Settings..." button on the right side of the ActionScript version and finally click in the target icon button. Then you only need to select one of the folders I told before.
All of this is better explained in the docs.


Now the Rjgtav's way.
In my way, you only need to copy the ("it" folder for AS2.0 or "it" and "com" folders for AS3.0) located under the respective folders that were previously mentioned to the folder of your project. So simple as that (at least for me it works). But I suggest you to use the one explained in the docs xD.


Important Note: You only need to do this about the API in the pc where the projects are. When you upload your game to your website, you only need to upload the .swf file, because when publishing, Flash compiles all the imported API's in the .swf file, saving some work.

Saturday 1 January 2011

SFS1X: Initial Server Configuration

Hello and welcome to the 1st tutorial of this blog. First of all, Happy New Year to everyone! Before starting the tutorial, I would like to talk a little about the blog and my objective while writing it.
I decided to write this blog because lately in the sfs community many people has asked questions that were already answered some time ago and also because I would like to share my knowledge and experience with the SmartFoxServer and Flash.
Now to the tutorial.
Today I'l explain how to initially configure the SmartFoxServer.


First you need to download SmartFoxServer from http://www.smartfoxserver.com/products/.


Warning: If you're using Windows Vista/7, please install in a different folder than the Program Files one (because of the write privileges).


Then, you need to open the port 9339 in the firewall and if you're behind a router, you need to forward that port to the internal ip of your pc. For further informations please check http://portforward.com/


After this you only need to execute the file start.bat (for Windows users) or the by executing the command ./sfs start (for Linux users).


This is better explained in http://www.smartfoxserver.com/docs/docPages/intro/installation.htm


Now the configuration part.


To configure the server you need to edit the config.xml file under [SmartFoxServer Installation Folder]\Server (You can edit it with any text editor like notepad)


The first parameter you need to set is the ServerIP. Here you set the ip you want the server to bind (your external ip given by http://whatismyip.org/ or http://www.whatismyip.com/, it doesn't matter).


Tip: If you are behind a router, i suggest you to put an * in the ServerIP. This way it will bind all the available socket addresses and you won't need to care about changing the ServerIP all the time anymore.


Then you need to set the ServerPort. Here you can set the port you want (don't forget to open it in the firewall and forward it if you're behind a router).


Warning: The port mustn't be used by any other program/software you have. That way the server won't work and will give startup errors.


If you want you can also configure initially the administrator login information. For that you only need to change the AdminLogin and AdminPassword parameters.


Of course you'll need to configure much more parameters (basically all of them), but this is the basic you need to put the server running.


For further information you can check the sfs docs (http://www.smartfoxserver.com/docs/)


If you have any questions, fell free to ask me (by commenting or by dropping me a pm in the sfs forums).
See you till the next tutorial ;-)