[Unity]Untiy-RPC-Sample

Untiy-RPC-Sample

使用UnityEngine中的NetWork建立的服務器類

LO_GameServer.cs

** 經過該工具類可以在Unity程序中快速的建立一個遊戲房間服務器,查詢房間列表,及發送消息功能 ** 服務器

using System; using UnityEngine; namespace LO_Tool { public class LO_GameServer:MonoBehaviour { #region 單例化 private LO_GameServer () {
		} private static GameObject s_LO_GameServer_object; private static LO_GameServer s_LO_GameServer = null; private static NetworkView s_LO_NetworkView = null; public static LO_GameServer DefaultServer
		{ get{ if (s_LO_GameServer == null) 
				{
					s_LO_GameServer_object = new GameObject("DefaultServer");
					s_LO_GameServer = s_LO_GameServer_object.AddComponent<LO_GameServer>();
					s_LO_NetworkView = s_LO_GameServer_object.AddComponent<NetworkView>();
				} return s_LO_GameServer;
			}
		} private static NetworkView DefalutNetworkView
		{ get{ return s_LO_NetworkView;
			}
		} #endregion /// <summary> /// init server... /// </summary> /// <param name="ip">Ip.</param> /// <param name="port">Port.</param> public bool InitServer(string ip,int port) { //set property MasterServer.ipAddress = ip;
			MasterServer.port = port; return true;
		} /// <summary> /// Starts the server. /// </summary> /// <returns><c>true</c>, if server was started, <c>false</c> otherwise.</returns> public bool StartServer() { //start... Network.InitializeServer(1000,25000,!Network.HavePublicAddress()); //register a game MasterServer.RegisterHost("Card","XiaoHao's Doudizhu"); return true;
		} public delegate void RequestRoomComplete(HostData[] list); private RequestRoomComplete complete_block = null; public RequestRoomComplete CompleteBlock{ set{
				complete_block = value;
			} get{ return complete_block;
			}
		} public void StartRequestRoom(RequestRoomComplete block) {
			LO_GameServer.DefaultServer.CompleteBlock = block;

			MasterServer.RequestHostList("Card");
		} public delegate void JoinHostRoomDelegate(int state); private JoinHostRoomDelegate join_delegate = null; public void JoinHostRoom(HostData room,JoinHostRoomDelegate block) { this.join_delegate = block;

			NetworkConnectionError error = Network.Connect(room.ip[0],room.port);

			Debug.Log(error);
		} public void SendGameMessage(string message) {
			LO_GameServer.DefalutNetworkView.RPC("RemoteReceiveMessage",RPCMode.All,message);
		}

		[RPC] public void RemoteReceiveMessage(string message) {
			Debug.Log(message);
		} #region Behaviour Actions /// <summary> /// some event notification from master server /// </summary> /// <param name="ev">Ev.</param> public void OnMasterServerEvent(MasterServerEvent ev) { switch (ev) { case MasterServerEvent.RegistrationSucceeded:
			{ break;
			} case MasterServerEvent.RegistrationFailedNoServer:
			{ break;
			} case MasterServerEvent.RegistrationFailedGameType:
			{ break;
			} case MasterServerEvent.RegistrationFailedGameName:
			{ break;
			} case MasterServerEvent.HostListReceived:
			{
				LO_GameServer.DefaultServer.CompleteBlock(MasterServer.PollHostList()); break;
			} default: break;
			}

		} public void OnPlayerConnected(NetworkPlayer player) {

		} public void OnConnectedToServer() { this.join_delegate(0);
			Debug.Log("OnConnectedToServer");
		} #endregion }
}

咱們發現幾點與一般單例類不一樣的地方 函數

  • LO_GameServer類繼承於MonoBehaviour腳本類
  • 靜態對象s_LO_GameServer,是經過AddComponent函數實例化的,這與Unity引擎腳本類的實例化機制有關
  • LO_GameServer單例類與其餘單例類不一樣的地方在於,須要多建立一個靜態的GameObject變量,用來存儲該單例腳本對象

除了以上幾點不一樣之處,在該類中一樣定義了幾個委託類型,用來作回調功能的處理 工具

  • RequestRoomComplete委託類型,當請求房間列表成功後就會調用該委託類型的變量complete_block
  • JoinHostRoomDelegate委託類型,當加入房間成功後就會調用該委託類型的變量join_delegate

應用舉例

private HostData[] room_list = null;
	private bool isConnected = false; void OnGUI()
	{ if (GUILayout.Button("StartServer")) 
		{
			LO_GameServer.DefaultServer.StartServer();
		} if (GUILayout.Button("RequestRoom")) 
		{
			LO_GameServer.DefaultServer.StartRequestRoom((HostData[] list)=>{ this.room_list = list;
			});
		} if (this.room_list != null) {
			GUILayout.BeginVertical();
			
			foreach (HostData item in this.room_list) 
			{
				GUILayout.BeginHorizontal();
				
				GUILayout.Label(item.ip[0],GUILayout.Width(200f),GUILayout.Height(40f));
				GUILayout.Label(item.gameName,GUILayout.Width(200f),GUILayout.Height(40f));

				string title = null;
				Action<HostData> action = null;

				Action<HostData> state_connect = (HostData data)=>{
					LO_GameServer.DefaultServer.SendGameMessage(user.ToString());
				};

				Action<HostData> state_no_connect = (HostData data) => 
				{
					LO_GameServer.DefaultServer.JoinHostRoom(data,(int state)=>{

						isConnected = state == 0;
						
					});
				}; if (isConnected) {
					title = "Send";
					action = state_connect;
				} else {
					title = "Connect";
					action = state_no_connect;
				} if (GUILayout.Button(title,GUILayout.Width(60f),GUILayout.Height(40f))) 
				{
					action(item);
				}
				
				GUILayout.EndHorizontal();
			}
			
			
			GUILayout.EndVertical();
		}
	}

使用C#語言中的System.Xml與System.IO庫完成實體對象與XML轉換的工具類

LO_XMLTool.cs

經過該工具類,可以快速的將C#中的實體對象與XML進行轉換,方便你們在編寫代碼完成進行數據交互的功能 this

using System; using System.Xml; using System.Xml.Serialization; using System.IO; namespace AssemblyCSharp { public class LO_XMLTool { #region 反序列化 /// <summary> /// 反序列化 /// </summary> /// <param name="type">類型</param> /// <param name="xml">XML字符串</param> /// <returns></returns> public static object Deserialize(Type type, string xml) { try { using (StringReader sr = new StringReader(xml))
				{
					XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(sr);
				}
			} catch (Exception e)
			{ return null;
			}
		} /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static object Deserialize(Type type, Stream stream) {
			XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(stream);
		} #endregion #region 序列化 /// <summary> /// 序列化 /// </summary> /// <param name="type">類型</param> /// <param name="obj">對象</param> /// <returns></returns> public static string Serializer(Type type, object obj) {
			MemoryStream Stream = new MemoryStream();
			XmlSerializer xml = new XmlSerializer(type); try { //序列化對象 xml.Serialize(Stream, obj);
			} catch (InvalidOperationException)
			{ throw;
			}
			Stream.Position = 0;
			StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd();
			
			sr.Dispose();
			Stream.Dispose(); return str;
		} #endregion }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息