查看: 2333|回复: 1
打印 上一主题 下一主题

[经验分享] 在SmartFoxServer上自定义公聊和私聊 4

[复制链接]

5552

主题

2

听众

8万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
11

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

跳转到指定楼层
楼主
发表于 2012-3-20 14:49:35 |只看该作者 |倒序浏览


四,在unity3d中创建一个C#文件。为了方便,这段代码是从SFS官网上下载的,对其进行了部分修改。官网提供的链接是:



http://119.40.0.4/data1/zip/a048746bd0687063688926869c2e4217 /SFS_CSharp_1.2.6.zip,我们用的是02_SimpleLobby这个例子。
对LobbyGUI.cs中做了如下修改:
1,private string extendName="";//声明一个扩展变量
public LobbyGUI(){

        extendName="publicInfomation";//服务器端扩展名,同config.xml中的扩展名配置一定要一到致。

}
// 发送自定义的聊天信息

smartFox.SendXtMessage(extendName,"pub",arr,SmartFoxClient.XTMSG_TYPE_STR);
// 接收服务器端传递过来的信息

    public void OnExtensionResponse(object data, string type) {

        // We only use XML based messages in this tutorial, so ignore string and json types

        if ( type == SmartFoxClient.XTMSG_TYPE_XML ) {

            // For XML based communication the data object is a SFSObject

            SFSObject dataObject = (SFSObject)data;

            switch(dataObject.GetString("_cmd")){

                case "pub"://公共聊天信息处理

                    //在聊天窗口中显示从服务器端发送来的聊天信息

                    lock (messagesLocker) {

                        messages.Add(dataObject.Get("username") + "    said :" + dataObject.Get("publicMessages"));

                    }

                  

                    chatScrollPosition.y = Mathf.Infinity;

                  

                    break;

                case "pra"://私人聊天信息处理                  

                  

                    break;

               

            }

           

        }

    }
2,完整的LobbyGUI.cs如下所示:
using UnityEngine;

using System;

using System.Collections;

using System.Collections.Generic;

using System.Runtime.Interopservices;

using System.Security.Permissions;

using System.Text;

using SmartFoxClientAPI;

using SmartFoxClientAPI.Data;
public class LobbyGUI : MonoBehaviour

{

    private SmartFoxClient smartFox;

    private string zone = "simpleChat";

    private string username = "";

    private string password = "";

    private string loginErrorMessage = "";

    private bool isLoggedIn;//是否登录成功率
    private bool roomListReceived = false;//接收房间列表
    private string newMessage = "";

    private ArrayList messages = new ArrayList();//信息集合

    // Locker to use for messages collection to ensure its cross-thread safety

    private System.Object messagesLocker = new System.Object();

   

    private Vector2 chatScrollPosition, userScrollPosition;
    private int roomSelection = 0;

    private string [] roomStrings;//房间集合

   

    private string extendName="";

   

    public GUISkin gSkin;

   

    public LobbyGUI(){

        extendName="publicInfomation";//服务器端扩展名

    }

    void Start()

    {

        if (SmartFox.initialized)

        {

            smartFox = SmartFox.Connection;

        }

        else

        {

            Application.LoadLevel("connection");

        }
        // Register callbacks

        SFSEvent.onLogin += OnLogin;

        SFSEvent.onLogout += OnLogout;

        SFSEvent.onConnectionLost += OnDisconnect;

        SFSEvent.onRoomListUpdate += OnRoomList;

        SFSEvent.onJoinRoom += OnJoinRoom;

        //SFSEvent.onPublicMessage += OnPublicMessage;

        SFSEvent.onExtensionResponse += OnExtensionResponse;

        SFSEvent.onDebugMessage += OnDebugMessage;

      

    }

   

    private void UnregisterSFSSceneCallbacks() {

        // This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene

        SFSEvent.onLogin -= OnLogin;

        SFSEvent.onLogout -= OnLogout;

        SFSEvent.onConnectionLost -= OnDisconnect;

        SFSEvent.onRoomListUpdate -= OnRoomList;

        SFSEvent.onJoinRoom -= OnJoinRoom;

        //SFSEvent.onPublicMessage -= OnPublicMessage;

        SFSEvent.onExtensionResponse -= OnExtensionResponse;

        SFSEvent.onDebugMessage -= OnDebugMessage;

      

    }
    // Various SFS callbacks

    void OnLogin(bool success, string name, string error)

    {

        Debug.Log("On Login callback got: " + success + " : " + error + " : " + name);
        if (success) {

            isLoggedIn = true;

        } else {

            loginErrorMessage = error;

            Debug.Log("Login error: "+error);

        }

    }
   

    void OnLogout()

    {

        Debug.Log("OnLogout");

        isLoggedIn = false;

        roomListReceived = false;

    }
    void OnDisconnect()

    {

        Debug.Log("OnDisconnect");

        isLoggedIn = false;

        roomListReceived = false;

        UnregisterSFSSceneCallbacks();

    }

   

    public void OnDebugMessage(string message)

    {

        Debug.Log("[SFS DEBUG] " + message);

    }
    void OnRoomList(Hashtable roomList)

    {   

        try {

            List<string> rooms = new List<string>();

           

            foreach (int roomId in roomList.Keys)

            {                  

                Room room = (Room)roomList[roomId];

               

                if (room.IsPrivate())

                {

                    continue;

                }

   

                Debug.Log("Room id: " + roomId + " has name: " + room.GetName());

               

                rooms.Add (room.GetName());

            }

         
            roomListReceived = true;

                  

            roomStrings = rooms.ToArray();

                                   

            // Users always have to be in a room, so lets go to the Hall as our main "lobby"

            if (smartFox.GetActiveRoom() == null) {

                //smartFox.AutoJoin();

                smartFox.JoinRoom("The Hall");

            }

                       

        }

        catch (Exception e) {

            Debug.Log("Room list error: "+e.Message+" "+e.StackTrace);

        }

    }
    void OnJoinRoom(Room room)

    {

        Debug.Log("Room " + room.GetName() + " joined successfully");

        lock (messagesLocker) {

            messages.Clear();

        }

    }
    void OnPublicMessage(string message, User sender, int roomId)

    {

        // We use lock here to ensure cross-thread safety on the messages collection

        lock (messagesLocker) {

            messages.Add(sender.GetName() + " said " + message);

        }

      

        chatScrollPosition.y = Mathf.Infinity;

        Debug.Log("User " + sender.GetName() + " said: " + message);

    }
   

   

    // Finally draw all the lobby GUI

    void OnGUI()

    {

        GUI.skin = gSkin;

   

        GUI.Label(new Rect(2, -2, 680, 70), "", "SFSLogo");   

      

        // Login

        if (!isLoggedIn)

        {

            GUI.Label(new Rect(10, 90, 100, 100), "Zone: ");

            zone = GUI.TextField(new Rect(100, 90, 200, 20), zone, 25);
            GUI.Label(new Rect(10, 116, 100, 100), "Userame: ");

            username = GUI.TextField(new Rect(100, 116, 200, 20), username, 25);
            GUI.Label(new Rect(10, 142, 100, 100), "assword: ");

            password = GUI.TextField(new Rect(100, 142, 200, 20), password, 4);
            GUI.Label(new Rect(10, 218, 100, 100), loginErrorMessage);
            if (GUI.Button(new Rect(100, 166, 100, 24), "Login")  || (Event.current.type == EventType.keyDown && Event.current.character == '
'))

            {

                smartFox.Login(zone, username, password);

            }

        }

        else

        {

            // Standard view

            if (GUI.Button(new Rect(580, 478, 90, 24), "Logout"))

            {

                smartFox.Logout();

            }
            // Basic info

            //GUI.Label(new Rect(10, 40, 200, 100), "Logged in as " + smartFox.myUserName);

            Room currentActiveRoom = smartFox.GetActiveRoom();
            if (currentActiveRoom != null)

            {

                GUI.Label(new Rect(498, 248, 180, 40), "Current room: " + currentActiveRoom.GetName());

            }   

           

            // Room list

            if (roomListReceived)

            {

                GUI.Box(new Rect(490, 80, 180, 170), "Room List");                  

               

                GUILayout.BeginArea (new Rect(500, 110, 150, 130));   

                  

                    roomSelection = GUILayout.SelectionGrid (roomSelection, roomStrings, 1, "RoomListButton");

                    if (roomStrings[roomSelection] != currentActiveRoom.GetName())

                    {

                        smartFox.JoinRoom(roomStrings[roomSelection]);

                    }

                  

                GUILayout.EndArea();

               

            }
            // Room chat window

            if (currentActiveRoom != null)

            {

           

                // User list

                GUI.Box(new Rect(490, 270, 180, 200), "Users");

               

                GUILayout.BeginArea (new Rect(500, 300, 150, 160));

                    userScrollPosition = GUILayout.BeginScrollView (userScrollPosition, GUILayout.Width (150), GUILayout.Height (160));

                        GUILayout.BeginVertical();
                            foreach (User user in currentActiveRoom.GetUserList().Values)

                            {

                                GUILayout.Label(user.GetName());

                            }

               

                        GUILayout.EndVertical();

                    GUILayout.EndScrollView ();

                GUILayout.EndArea();

                     
                // Chat history

                GUI.Box(new Rect(10, 80, 470, 390), "Chat");
                GUILayout.BeginArea (new Rect(20, 110, 450, 350));

                    chatScrollPosition = GUILayout.BeginScrollView (chatScrollPosition, GUILayout.Width (450), GUILayout.Height (350));

                        GUILayout.BeginVertical();

                       

                        // We use lock here to ensure cross-thread safety on the messages collection

                        lock (messagesLocker) {

                            foreach (string message in messages)

                            {

                                GUILayout.Label(message);

                            }

                        }

               

                        GUILayout.EndVertical();

                    GUILayout.EndScrollView ();

                GUILayout.EndArea();
                // Send message

                newMessage = GUI.TextField(new Rect(10, 480, 370, 20), newMessage, 50);

                if (GUI.Button(new Rect(390, 478, 90, 24), "Send")  || (Event.current.type == EventType.keyDown && Event.current.character == '
'))

                {

                  

                    //将以SmartFoxClient.XTMSG_TYPE_STR协议发送

                    ArrayList arr=new ArrayList();

                    arr.Add(newMessage);

                  

                    /*将以SmartFoxClient.XTMSG_TYPE_JSON协议发送

                    Hashtable bulletInfo = new Hashtable();

                    bulletInfo[0] = newMessage;

                    //bulletInfo["posx"] = 100;

                    */

                  

                    //smartFox.SendPublicMessage(newMessage, currentActiveRoom.GetId());//官网的提供的发送聊天信息的方法

                  

                    //发送自定义的聊天信息

                    smartFox.SendXtMessage(extendName,"pub",arr,SmartFoxClient.XTMSG_TYPE_STR);

                    //smartFox.SendXtMessage(extendName,"pub",bulletInfo,SmartFoxClient.XTMSG_TYPE_JSON);

                  

                    newMessage = "";

                }

               

            }

        }

    }

   

    //接收服务器端传递过来的信息

    public void OnExtensionResponse(object data, string type) {

        // We only use XML based messages in this tutorial, so ignore string and json types

        if ( type == SmartFoxClient.XTMSG_TYPE_XML ) {

            // For XML based communication the data object is a SFSObject

            SFSObject dataObject = (SFSObject)data;

            switch(dataObject.GetString("_cmd")){

                case "pub"://公共聊天信息处理

                    //在聊天窗口中显示从服务器端发送来的聊天信息

                    lock (messagesLocker) {

                        messages.Add(dataObject.Get("username") + "    said :" + dataObject.Get("publicMessages"));

                    }

                  

                    chatScrollPosition.y = Mathf.Infinity;

                  

                    break;

                case "pra"://私人聊天信息处理                  

                  

                    break;

               

            }

           

        }

    }

   

}



unity3d8.com
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

hyui    

1

主题

2

听众

6671

积分

高级设计师

Rank: 6Rank: 6

纳金币
2715
精华
0

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

沙发
发表于 2014-1-4 01:03:35 |只看该作者
Thanks for the hands up!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

关闭

站长推荐上一条 /1 下一条

手机版|纳金网 ( 闽ICP备08008928号

GMT+8, 2024-5-14 06:27 , Processed in 0.095302 second(s), 28 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部