Client API - C# Simple Example

Post here your questions about the Unity / .Net / Mono / Windows 8 / Windows Phone 8 API for SFS2X

Moderators: Lapo, Bax

vincentgtocch
Posts: 4
Joined: 08 Feb 2010, 04:44

Client API - C# Simple Example

Postby vincentgtocch » 23 May 2012, 10:29

Dear Sir,

Would you please help to provide the source code of C# which have a clear explaination how to connect to server, build zone, room and chat between clients. Thanks


Best Regards,
Vincent Chan
User avatar
Bax
Site Admin
Posts: 4609
Joined: 29 Mar 2005, 09:50
Location: Italy
Contact:

Re: Client API - C# Simple Example

Postby Bax » 24 May 2012, 09:00

Please check the online documentation for full tutorials and examples: http://docs2x.smartfoxserver.com/Exampl ... troduction
Paolo Bax
The SmartFoxServer Team
ThomasLund
Posts: 1297
Joined: 14 Mar 2008, 07:52
Location: Sweden

Re: Client API - C# Simple Example

Postby ThomasLund » 25 May 2012, 21:22

And if you need a starter project for a console:

Code: Select all

using System;
using SmartFoxClientAPI;

namespace sfssimpleconsoletest
{
   class MainClass
   {
      public static void Main (string[] args)
      {
         SFSClient client = new SFSClient();
         client.Connect();
        }
   }
   
   public class SFSClient {
      private string ip = "127.0.0.1";
        private int port = 9339;
        private string status = "";
        private SmartFoxClient smartFox;
        private string zone = "simpleChat";
        private string username = "";
        private string password = "";
        private bool bo;
      
      public SFSClient ()
      {
         Console.WriteLine ("Start connection!");

            smartFox = new SmartFoxClient();
            SFSEvent.onConnection += OnConnection;
            SFSEvent.onConnectionLost += OnConnectionLost;
      }
      
      public void Connect() {
            smartFox.Connect(ip, port);             
        }


        //----------------------------------------------------------
        // Handle connection response from server
        //----------------------------------------------------------
        void OnConnection(bool success, string error)
        {
            if (success)
            Console.WriteLine ("Connected");
            else
            Console.WriteLine ("Could not connect");
        }

        void OnConnectionLost()
        {
         Console.WriteLine ("Connection lost / no connection to server");
        }
   }
}

Full Control - maker of Unity/C# and Java SFS API and indie games
Follow on twitter: http://twitter.com/thomas_h_lund
User avatar
Chrisx84
Posts: 1
Joined: 24 Jul 2012, 16:24
Location: Hamilton, Ontario, Canada

Re: Client API - C# Simple Example

Postby Chrisx84 » 24 Jul 2012, 16:28

I'm having one hell of a time to with connecting my web player based game to my smartfox server and the docs are not noob friendly and the sample codes gives me errors.
I am however very new to C# coding, i prefer to script in js when it comes to unity programming.
If there are starter code i can then work and learn off of then that be great, if not then i might have to go get a winblows server to run Photon off of.
Currently got Smart Fox on a Ubuntu but sadly Photon does not support Linux.
Thanks in advanced, you can email me at chrisx84@live.ca
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 06 Aug 2012, 00:32

Good Afternoon,

Is there an example for use with SmartFoxServer v2? The example above is for v1 as the SmartFoxClientAPI namespace doesn't exist in v2. And unfortunately,the unity examples does not contain any c# source codes.

After some fiddling around, I got a partially working example for v2, based on the code above, but updated ..

Code: Select all

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Requests;

    public class SFSClient
    {
        private string ip = "127.0.0.1";
        private int port = 9933;
        private string status = "";
        private SmartFox smartFox;
        private string username = "";
        private string password = "";
        private string zone = "BasicExamples";
        private bool bo;

        public SFSClient()
        {
            Console.WriteLine("adding events");
            smartFox = new SmartFox();
            smartFox.AddEventListener(SFSEvent.CONNECTION, OnConnection);
            smartFox.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
            smartFox.AddEventListener(SFSEvent.LOGIN, OnLogin);
            smartFox.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);

            Console.WriteLine("events added");
        }

        public void Connect()
        {
            Console.WriteLine("trying to connect?");
            smartFox.Connect(ip, port);
 
            LoginRequest loginReq = new LoginRequest(username, password, zone);
            smartFox.Send(loginReq);
        }

        //----------------------------------------------------------
        // Handle connection response from server
        //----------------------------------------------------------
        void OnConnection(BaseEvent evt)
        {
            Console.WriteLine("connected?");
            bool success = (bool)evt.Params["success"];

            if (success)
            {
                Console.WriteLine("Connected");
            }
            else
            {
                Console.WriteLine("Could not connect");
            }
        }

        public void OnConnectionLost(BaseEvent evt)
        {
            Console.WriteLine("Connection lost / no connection to server");
        }

        public void OnLogin(BaseEvent evt)
        {
            Console.WriteLine("Login success!");
        }

        public void OnLoginError(BaseEvent evt)
        {
            Console.WriteLine("Unable to log in");
        }
    }



Code: Select all

    class Program
    {
        static void Main(string[] args)
        {
            SFSClient client = new SFSClient();
            client.Connect();
            Console.ReadLine();
        }
    }


Unforunately, events never fire.
User avatar
Lapo
Site Admin
Posts: 23008
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Client API - C# Simple Example

Postby Lapo » 07 Aug 2012, 08:30

@Zanpher: Bax has already posted the link --> http://docs2x.smartfoxserver.com/Exampl ... troduction
Lapo
--
gotoAndPlay()
...addicted to flash games
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 07 Aug 2012, 21:30

Okay. Right now I have the events running via loop in a console (at this time) so that the events will fire (sorta). Is there some sort of way to unpackage those unity packages so we can see the C#, without installing unity on my machine? I have no reason to use unity at all, only need the c# code. (I am going the XNA route here).
User avatar
Lapo
Site Admin
Posts: 23008
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Client API - C# Simple Example

Postby Lapo » 08 Aug 2012, 09:39

The current format of Unity bundles (.unitypackage) is a single compressed file.
This post from the Unity forums might help:
http://answers.unity3d.com/questions/21 ... unity.html
Lapo

--

gotoAndPlay()

...addicted to flash games
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 09 Aug 2012, 01:13

Thanks for the info.

I ended up using 7-zip to decompress the files. And .,.. There are tons of guid named folders with no source code.

Most folders have the following files:

._asset
metaData
pathname
preview.png

After opening each of the folders and files in there, they ended up being binary files and no source code.

Are there actual working c# examples available?
User avatar
Lapo
Site Admin
Posts: 23008
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Client API - C# Simple Example

Postby Lapo » 09 Aug 2012, 07:59

If that doesn't work you can get Unity for free and check the code with it.
Lapo

--

gotoAndPlay()

...addicted to flash games
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 09 Aug 2012, 15:02

Thanks for the response.

That is exactly what I am trying to prevent. Unity on the machine I am on is a no go.

Are there any chance for a .NET API with examples for SFS? I wouldn't want to waste any more of your time or my time if there isn't one.
ThomasLund
Posts: 1297
Joined: 14 Mar 2008, 07:52
Location: Sweden

Re: Client API - C# Simple Example

Postby ThomasLund » 10 Aug 2012, 12:34

I've pasted a class below that is a console thing. Not super prettified, but I'm certain you can pull things apart.

Hope that helps

Code: Select all

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities;
using Sfs2X.Entities.Data;
using Sfs2X.Requests;
using Sfs2X.Logging;


namespace SFS2XByteSizeTest
{
   public class Sender
   {
      private string serverName = "127.0.0.1";
      private int serverPort = 9933;
      private SmartFox smartFox;
      private SFSObject requestObject;
      
      public readonly static string ExtName = "__lib__";  // The server extension we work with
      public readonly static string ExtClass = "dk.fullcontrol.XXXXXExtension";

      
      public void SendToServer (string sceneName, XmlDocument levelDoc, XmlDocument sceneDoc)
      {
         Console.WriteLine ("Preparing upload");
                  
         // Lets put level xml into sfsobject
         requestObject = new SFSObject ();
         requestObject.PutUtfString ("sceneName", sceneName);
         
         // SFS2X can only handle <32kb strings - lets send as byte array instead
         System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding ();
         byte[] levelXmlBytes = encoding.GetBytes ( convertXmlToString(levelDoc) );
         requestObject.PutByteArray ("levelXml", new Sfs2X.Util.ByteArray (levelXmlBytes));
         
         byte[] sceneXmlBytes = encoding.GetBytes ( convertXmlToString(sceneDoc) );
         requestObject.PutByteArray ("sceneXml", new Sfs2X.Util.ByteArray (sceneXmlBytes));
         
         // Scene data
         requestObject.PutInt ("numberOfCharacters", 2);
         requestObject.PutUtfString ("urlToUnityClient", "XXX");
         
         smartFox = new SmartFox (false);
         // Register callback delegate
         smartFox.AddEventListener (SFSEvent.CONNECTION, OnConnection);
         smartFox.AddEventListener (SFSEvent.LOGIN, OnLogin);
         smartFox.AddEventListener (SFSEvent.ROOM_JOIN, OnJoinRoom);
         smartFox.AddEventListener (SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
         smartFox.AddLogListener (LogLevel.ERROR, OnDebugMessage);
         Console.WriteLine ("Connecting... ");
         smartFox.ThreadSafeMode = false;
         smartFox.Connect (serverName, serverPort);
         
      }

      public string convertXmlToString(XmlDocument xml) {
         // Convert to string
         StringWriter sw = new StringWriter ();
         XmlTextWriter xw = new XmlTextWriter (sw);
         xml.WriteTo (xw);
         string xmlString = sw.ToString ();
         // Cleanup
         xw.Close ();
         sw.Close ();
         
         Console.WriteLine("Converted to string size: " + xmlString.Length);
         
         return xmlString;
      }
      
      void OnInspectorUpdate ()
      {
         if (smartFox != null) {
            smartFox.ProcessEvents ();
         }
      }

      public void OnConnection (BaseEvent evt)
      {
         bool success = (bool)evt.Params["success"];
         string error = (string)evt.Params["error"];
         
         Console.WriteLine ("On Connection callback got: " + success + " (error : <" + error + ">)");
         
         if (success) {
            Console.WriteLine ("Connected");
            SmartFoxConnection.Connection = smartFox;
            smartFox.Send (new LoginRequest ("XXXXX", "XXXXXX", "XXX"));
         } else {
            Console.WriteLine ("Connection failed");
         }
      }

      public void OnLogin (BaseEvent evt)
      {
         try {
            bool success = true;
            if (evt.Params.ContainsKey ("success") && !(bool)evt.Params["success"]) {
               Console.WriteLine ("Login error: " + (string)evt.Params["errorMessage"]);
            } else {
               Console.WriteLine ("Logged in successfully");
               
               RoomSettings settings = new RoomSettings ("islet_adminroom");
               settings.GroupId = "game";
               settings.IsGame = false;
               settings.MaxUsers = 4;
               settings.MaxSpectators = 0;
               settings.Extension = new RoomExtension (ExtName, ExtClass);
               smartFox.Send (new CreateRoomRequest (settings, true, smartFox.LastJoinedRoom));
            }
         } catch (Exception ex) {
            Console.WriteLine ("Exception handling login request: " + ex.Message + " " + ex.StackTrace);
         }
      }

      public void OnJoinRoom (BaseEvent evt)
      {
         Room room = (Room)evt.Params["room"];
         if (room.Name == "islet_adminroom") {
            Console.WriteLine ("Joined game room " + room.Name);
            
            _SendIt ();
            
         } else {
            Console.WriteLine ("Join room failed");
         }
      }

      private void _SendIt ()
      {
         Console.WriteLine ("Sending to server at " + DateTime.Now.ToLongTimeString());
         Console.WriteLine("***");
         Room room = smartFox.LastJoinedRoom;
         ExtensionRequest request = new ExtensionRequest ("admin.saveXML", requestObject, room);
         Console.WriteLine("***");
         Console.WriteLine ("Build request - ready to send " + DateTime.Now.ToLongTimeString());
         Console.WriteLine("***");
         smartFox.Send (request);
         Console.WriteLine("***");
         Console.WriteLine ("End sending to server at " + DateTime.Now.ToLongTimeString());
      }

      // This method handles all the responses from the server
      private void OnExtensionResponse (BaseEvent evt)
      {
         try {
            string cmd = (string)evt.Params["cmd"];
            ISFSObject dt = (SFSObject)evt.Params["params"];
            
            if (cmd == "saveXMLOK") {
               Console.WriteLine ("File written to server");
            } else if (cmd == "saveXMLKO") {
               Console.WriteLine ("Error from server");
            }
            smartFox.Disconnect ();
            
         } catch (Exception e) {
            Console.WriteLine ("Unknown error sending XML");
            smartFox.Disconnect ();
         }
         
           if (smartFox.IsConnected) {
               smartFox.Disconnect();
           }

         

      }
      
      public void OnDebugMessage (BaseEvent evt)
      {
         string message = (string)evt.Params["message"];
         Console.WriteLine ("[SFS DEBUG] " + message);
      }
      
      
      
   }
}
Full Control - maker of Unity/C# and Java SFS API and indie games

Follow on twitter: http://twitter.com/thomas_h_lund
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 12 Aug 2012, 18:31

Thanks for the code. I'll need to take a gander at it, in some spare time.
Zanpher
Posts: 96
Joined: 05 Oct 2009, 23:15

Re: Client API - C# Simple Example

Postby Zanpher » 26 Nov 2012, 21:12

I finally have time to look through this.

Thank you for the code.

That difference was the threaded mode flag, once that was set to false, smartfox started firing events properly :) Thank you!

Return to “SFS2X C# API”

Who is online

Users browsing this forum: No registered users and 27 guests