StartingHostState.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using Unity.Netcode;
  3. using UnityEngine;
  4. //StartHost开启服务端
  5. class StartingHostState : OnlineState
  6. {
  7. ConnectionMethodIP m_ConnectionMethod;
  8. public StartingHostState Configure()
  9. {
  10. m_ConnectionMethod = m_ConnectionManager.ConnectionMethod;
  11. return this;
  12. }
  13. public override void Enter()
  14. {
  15. StartHost();
  16. }
  17. public override void Exit()
  18. {
  19. }
  20. //StartHost失败
  21. public override void OnClientDisconnect(ulong clientId)
  22. {
  23. if(clientId == m_ConnectionManager.NetworkManager.LocalClientId)
  24. {
  25. StartHostFailed();
  26. }
  27. }
  28. //StartHost失败。跳转到OfflineState
  29. void StartHostFailed()
  30. {
  31. MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.StartHostFailed);
  32. m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
  33. }
  34. //StartHost成功,跳转到HostingState
  35. public override void OnServerStarted()
  36. {
  37. MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.Success);
  38. m_ConnectionManager.ChangeState(m_ConnectionManager.m_Hosting);
  39. }
  40. //此处的检查主要是针对Host的客户端自己连接。当启动Host时,就会创建本地客户端,并连接触发此处调用
  41. public override void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
  42. {
  43. var connectionData = request.Payload;
  44. var clientId = request.ClientNetworkId;
  45. if(clientId == m_ConnectionManager.NetworkManager.LocalClientId)
  46. {
  47. var payload = System.Text.Encoding.UTF8.GetString(connectionData);
  48. var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload);
  49. //保存Host客户端登录数据
  50. PlayerManager.Instance.SetupConnectingPlayerSessionData(clientId, connectionPayload.playerId,
  51. new PlayerData(clientId, connectionPayload, true));
  52. response.Approved = true;
  53. //Host客户端,需要生成预设物体
  54. response.CreatePlayerObject = true;
  55. }
  56. }
  57. //启动服务端
  58. async void StartHost()
  59. {
  60. try
  61. {
  62. //设置IP、端口
  63. await m_ConnectionMethod.SetupHostConnectionAsync();
  64. //开启Host
  65. if(!m_ConnectionManager.NetworkManager.StartHost())
  66. {
  67. //如果启动失败
  68. OnClientDisconnect(m_ConnectionManager.NetworkManager.LocalClientId);
  69. }
  70. }
  71. catch(Exception)
  72. {
  73. StartHostFailed();
  74. throw;
  75. }
  76. }
  77. }