Quantcast
Channel: Programming – Xinyustudio
Viewing all articles
Browse latest Browse all 284

Using SmartFox with C# (II) : Login and join room

$
0
0

The next step after connection with SmartFox server might be login to SmartFox.  If you wish to know how to connect to SmartFox server, refer to this post. Try below code to login to SmartFox:

using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Requests;
using System;

namespace TestSmartFox
{
    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();
//Important! Set it to true in Unity3D client.ThreadSafeMode = false;
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"); var request = new LoginRequest("Tracy", "", zone); //[1] client.Send(request); //[2] }); client.AddEventListener(SFSEvent.LOGIN, (evt) => { //[3] Console.WriteLine("The User login success"); }); client.Connect(serverIP, serverPort);
} } }

It is very simple to login using the client API:

  1. First create a login request, with given user name, password (empty string “” here) and which zone to login;
  2. Send the request using the SmartFox client;
  3. When the user logins, you will get notified

Check the results using AdminTool, you will clearly see this log:

image

Once Logined, you can then retrieve all the rooms and select one of the room to join in,  add or edit below code:

client.AddEventListener(SFSEvent.ROOM_JOIN, (evt) =>
            {
                Console.WriteLine("Join room success");
            });

client.AddEventListener(SFSEvent.LOGIN, (evt) => {
                Console.WriteLine("The User login success");
                var rooms = client.RoomList;                                         //[1]
                rooms.ForEach((room) => Console.WriteLine(room.Name));
                if (rooms.Count > 0)
                {
                    var request = new JoinRoomRequest(client.RoomList.First().Name); //[2]
                    client.Send(request);                                            //[3] 
                }
            });

Here, we can retrieve all rooms in the zone by calling Line [1], and then join one of them as shown in Line [2-3] above. Pretty simple & straightforward! Running the code above, we can see:

image

image

Happy coding!


Viewing all articles
Browse latest Browse all 284

Trending Articles