使用NetworkTransport集成

如果在集成Unity Multiplayer Services时需要最大的灵活性,则可以NetworkTransport直接使用该类。此方法需要更多的代码,但可以让您控制游戏与多人游戏服务集成的细节。

这是一个如何直接使用NetworkTransport类连接的示例:

  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using UnityEngine.Networking.Types;
  4. using UnityEngine.Networking.Match;
  5. using System.Collections.Generic;
  6. public class DirectSetup : MonoBehaviour
  7. {
  8. // Matchmaker related
  9. List<MatchInfoSnapshot> m_MatchList = new List<MatchInfoSnapshot>();
  10. bool m_MatchCreated;
  11. bool m_MatchJoined;
  12. MatchInfo m_MatchInfo;
  13. string m_MatchName = "NewRoom";
  14. NetworkMatch m_NetworkMatch;
  15. // Connection/communication related
  16. int m_HostId = -1;
  17. // On the server there will be multiple connections, on the client this will only contain one ID
  18. List<int> m_ConnectionIds = new List<int>();
  19. byte[] m_ReceiveBuffer;
  20. string m_NetworkMessage = "Hello world";
  21. string m_LastReceivedMessage = "";
  22. NetworkWriter m_Writer;
  23. NetworkReader m_Reader;
  24. bool m_ConnectionEstablished;
  25. const int k_ServerPort = 25000;
  26. const int k_MaxMessageSize = 65535;
  27. void Awake()
  28. {
  29. m_NetworkMatch = gameObject.AddComponent<NetworkMatch>();
  30. }
  31. void Start()
  32. {
  33. m_ReceiveBuffer = new byte[k_MaxMessageSize];
  34. m_Writer = new NetworkWriter();
  35. // While testing with multiple standalone players on one machine this will need to be enabled
  36. Application.runInBackground = true;
  37. }
  38. void OnApplicationQuit()
  39. {
  40. NetworkTransport.Shutdown();
  41. }
  42. void OnGUI()
  43. {
  44. if (string.IsNullOrEmpty(Application.cloudProjectId))
  45. GUILayout.Label("You must set up the project first. See the Multiplayer tab in the Service Window");
  46. else
  47. GUILayout.Label("Cloud Project ID: " + Application.cloudProjectId);
  48. if (m_MatchJoined)
  49. GUILayout.Label("Match joined '" + m_MatchName + "' on Matchmaker server");
  50. else if (m_MatchCreated)
  51. GUILayout.Label("Match '" + m_MatchName + "' created on Matchmaker server");
  52. GUILayout.Label("Connection Established: " + m_ConnectionEstablished);
  53. if (m_MatchCreated || m_MatchJoined)
  54. {
  55. GUILayout.Label("Relay Server: " + m_MatchInfo.address + ":" + m_MatchInfo.port);
  56. GUILayout.Label("NetworkID: " + m_MatchInfo.networkId + " NodeID: " + m_MatchInfo.nodeId);
  57. GUILayout.BeginHorizontal();
  58. GUILayout.Label("Outgoing message:");
  59. m_NetworkMessage = GUILayout.TextField(m_NetworkMessage);
  60. GUILayout.EndHorizontal();
  61. GUILayout.Label("Last incoming message: " + m_LastReceivedMessage);
  62. if (m_ConnectionEstablished && GUILayout.Button("Send message"))
  63. {
  64. m_Writer.SeekZero();
  65. m_Writer.Write(m_NetworkMessage);
  66. byte error;
  67. for (int i = 0; i < m_ConnectionIds.Count; ++i)
  68. {
  69. NetworkTransport.Send(m_HostId,
  70. m_ConnectionIds[i], 0, m_Writer.AsArray(), m_Writer.Position, out error);
  71. if ((NetworkError)error != NetworkError.Ok)
  72. Debug.LogError("Failed to send message: " + (NetworkError)error);
  73. }
  74. }
  75. if (GUILayout.Button("Shutdown"))
  76. {
  77. m_NetworkMatch.DropConnection(m_MatchInfo.networkId,
  78. m_MatchInfo.nodeId, 0, OnConnectionDropped);
  79. }
  80. }
  81. else
  82. {
  83. if (GUILayout.Button("Create Room"))
  84. {
  85. m_NetworkMatch.CreateMatch(m_MatchName, 4, true, "", "", "", 0, 0, OnMatchCreate);
  86. }
  87. if (GUILayout.Button("Join first found match"))
  88. {
  89. m_NetworkMatch.ListMatches(0, 1, "", true, 0, 0, (success, info, matches) =>
  90. {
  91. if (success && matches.Count > 0)
  92. m_NetworkMatch.JoinMatch(matches[0].networkId, "", "", "", 0, 0, OnMatchJoined);
  93. });
  94. }
  95. if (GUILayout.Button("List rooms"))
  96. {
  97. m_NetworkMatch.ListMatches(0, 20, "", true, 0, 0, OnMatchList);
  98. }
  99. if (m_MatchList.Count > 0)
  100. {
  101. GUILayout.Label("Current rooms:");
  102. }
  103. foreach (var match in m_MatchList)
  104. {
  105. if (GUILayout.Button(match.name))
  106. {
  107. m_NetworkMatch.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined);
  108. }
  109. }
  110. }
  111. }
  112. public void OnConnectionDropped(bool success, string extendedInfo)
  113. {
  114. Debug.Log("Connection has been dropped on matchmaker server");
  115. NetworkTransport.Shutdown();
  116. m_HostId = -1;
  117. m_ConnectionIds.Clear();
  118. m_MatchInfo = null;
  119. m_MatchCreated = false;
  120. m_MatchJoined = false;
  121. m_ConnectionEstablished = false;
  122. }
  123. public virtual void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
  124. {
  125. if (success)
  126. {
  127. Debug.Log("Create match succeeded");
  128. Utility.SetAccessTokenForNetwork(matchInfo.networkId, matchInfo.accessToken);
  129. m_MatchCreated = true;
  130. m_MatchInfo = matchInfo;
  131. StartServer(matchInfo.address, matchInfo.port, matchInfo.networkId,
  132. matchInfo.nodeId);
  133. }
  134. else
  135. {
  136. Debug.LogError("Create match failed: " + extendedInfo);
  137. }
  138. }
  139. public void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
  140. {
  141. if (success && matches != null)
  142. {
  143. m_MatchList = matches;
  144. }
  145. else if(!success)
  146. {
  147. Debug.LogError("List match failed: " + extendedInfo);
  148. }
  149. }
  150. // When we've joined a match we connect to the server/host
  151. public virtual void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
  152. {
  153. if (success)
  154. {
  155. Debug.Log("Join match succeeded");
  156. Utility.SetAccessTokenForNetwork(matchInfo.networkId, matchInfo.accessToken);
  157. m_MatchJoined = true;
  158. m_MatchInfo = matchInfo;
  159. Debug.Log("Connecting to Address:" + matchInfo.address +
  160. " Port:" + matchInfo.port +
  161. " NetworKID: " + matchInfo.networkId +
  162. " NodeID: " + matchInfo.nodeId);
  163. ConnectThroughRelay(matchInfo.address, matchInfo.port, matchInfo.networkId,
  164. matchInfo.nodeId);
  165. }
  166. else
  167. {
  168. Debug.LogError("Join match failed: " + extendedInfo);
  169. }
  170. }
  171. void SetupHost(bool isServer)
  172. {
  173. Debug.Log("Initializing network transport");
  174. NetworkTransport.Init();
  175. var config = new ConnectionConfig();
  176. config.AddChannel(QosType.Reliable);
  177. config.AddChannel(QosType.Unreliable);
  178. var topology = new HostTopology(config, 4);
  179. if (isServer)
  180. m_HostId = NetworkTransport.AddHost(topology, k_ServerPort);
  181. else
  182. m_HostId = NetworkTransport.AddHost(topology);
  183. }
  184. void StartServer(string relayIp, int relayPort, NetworkID networkId, NodeID nodeId)
  185. {
  186. SetupHost(true);
  187. byte error;
  188. NetworkTransport.ConnectAsNetworkHost(
  189. m_HostId, relayIp, relayPort, networkId, Utility.GetSourceID(), nodeId, out error);
  190. }
  191. void ConnectThroughRelay(string relayIp, int relayPort, NetworkID networkId, NodeID nodeId)
  192. {
  193. SetupHost(false);
  194. byte error;
  195. NetworkTransport.ConnectToNetworkPeer(
  196. m_HostId, relayIp, relayPort, 0, 0, networkId, Utility.GetSourceID(), nodeId, out error);
  197. }
  198. void Update()
  199. {
  200. if (m_HostId == -1)
  201. return;
  202. var networkEvent = NetworkEventType.Nothing;
  203. int connectionId;
  204. int channelId;
  205. int receivedSize;
  206. byte error;
  207. // Get events from the relay connection
  208. networkEvent = NetworkTransport.ReceiveRelayEventFromHost(m_HostId, out error);
  209. if (networkEvent == NetworkEventType.ConnectEvent)
  210. Debug.Log("Relay server connected");
  211. if (networkEvent == NetworkEventType.DisconnectEvent)
  212. Debug.Log("Relay server disconnected");
  213. do
  214. {
  215. // Get events from the server/client game connection
  216. networkEvent = NetworkTransport.ReceiveFromHost(m_HostId, out connectionId, out channelId,
  217. m_ReceiveBuffer, (int)m_ReceiveBuffer.Length, out receivedSize, out error);
  218. if ((NetworkError)error != NetworkError.Ok)
  219. {
  220. Debug.LogError("Error while receiveing network message: " + (NetworkError)error);
  221. }
  222. switch (networkEvent)
  223. {
  224. case NetworkEventType.ConnectEvent:
  225. {
  226. Debug.Log("Connected through relay, ConnectionID:" + connectionId +
  227. " ChannelID:" + channelId);
  228. m_ConnectionEstablished = true;
  229. m_ConnectionIds.Add(connectionId);
  230. break;
  231. }
  232. case NetworkEventType.DataEvent:
  233. {
  234. Debug.Log("Data event, ConnectionID:" + connectionId +
  235. " ChannelID: " + channelId +
  236. " Received Size: " + receivedSize);
  237. m_Reader = new NetworkReader(m_ReceiveBuffer);
  238. m_LastReceivedMessage = m_Reader.ReadString();
  239. break;
  240. }
  241. case NetworkEventType.DisconnectEvent:
  242. {
  243. Debug.Log("Connection disconnected, ConnectionID:" + connectionId);
  244. break;
  245. }
  246. case NetworkEventType.Nothing:
  247. break;
  248. }
  249. } while (networkEvent != NetworkEventType.Nothing);
  250. }
  251. }

?