Despite that SmartFox has offered a Unity3D package for easy access SmartFox functionalities for game developers, however it is not very straightforward to directly get to know how to consume SmartFox with C# (Mono), particularly in a step-by-step fashion. This post offers a concise introduction on how to get started with SmartFox in C# in 2 minutes. Hope you love it …
Server setup
- Got o SmartFoxServer web site
- Download and install the latest server in your computer
C# Client
- Got o SmartFoxServer web site
- Download the Client API
- Extract the downloaded zip file, and grab the dll for further use.
Create a C# console application, add reference to the above grabbed dll file, add below code:
using Sfs2X; using Sfs2X.Util; using System; class Program { static private SmartFox client; static private string serverIP = "127.0.0.1"; static private int serverPort = 9933; //8888 for WebSocket static public string zone = "BasicExamples"; static public bool debug = true; static void Main(string[] args) { client = new SmartFox(debug); ConfigData cfg = new ConfigData() { Host = serverIP, Port = serverPort, Zone = "BasicExamples", //Debug = debug //This also works }; client.Connect(cfg); while (client.IsConnecting) { Console.WriteLine("Connecting ..."); } Console.WriteLine(client.IsConnected ? "Successfully connected to SmartFox Server" : "Failed to connect to SmartFox Server"); } }
Results:
You might find that the above code uses while(…), which implements the polling pattern, i.e. the thread keeps checking if connection is established, which is less efficient and elegant, so a revised version might be as following, which is event driven:
class Program
{
static private SmartFox client;
static private string serverIP = “127.0.0.1”;
static private int serverPort = 9933;
static public string zone = “BasicExamples”;
static public bool debug = true;
static void Main(string[] args)
{
client = new SmartFox();
client.ThreadSafeMode = false; //Important!
client.AddEventListener(SFSEvent.CONNECTION, (evt) =>
{
bool bSuccess = (bool)evt.Params[“success”];
Console.WriteLine(client.IsConnected ?
“Successfully connected to SmartFox Server” :
“Failed to connect to SmartFox Server”);
});
client.Connect(serverIP, serverPort);
}
}
Note that in this version:
-
ConfigData is not used, and client.Connect(…); is called, which is a little bit concise;
-
client.ThreadSafeMode = false; this is important if you run this code in a console or standalone application, otherwise, the anonymous On connection event handler will NOT be called.
-
If you are running SmartFox client in Unity3D, set client.ThreadSafeMode = true;