ConnectionAPISample.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #if !BESTHTTP_DISABLE_SIGNALR
  2. using System;
  3. using UnityEngine;
  4. using BestHTTP.SignalR;
  5. using BestHTTP.Examples;
  6. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  7. using BestHTTP.Cookies;
  8. #endif
  9. public sealed class ConnectionAPISample : MonoBehaviour
  10. {
  11. readonly Uri URI = new Uri("https://besthttpsignalr.azurewebsites.net/raw-connection/");
  12. /// <summary>
  13. /// Possible message types that the client can send to the server
  14. /// </summary>
  15. enum MessageTypes
  16. {
  17. Send, // 0
  18. Broadcast, // 1
  19. Join, // 2
  20. PrivateMessage, // 3
  21. AddToGroup, // 4
  22. RemoveFromGroup, // 5
  23. SendToGroup, // 6
  24. BroadcastExceptMe, // 7
  25. }
  26. #region Private Fields
  27. /// <summary>
  28. /// Reference to the SignalR Connection
  29. /// </summary>
  30. Connection signalRConnection;
  31. // Input strings
  32. string ToEveryBodyText = string.Empty;
  33. string ToMeText = string.Empty;
  34. string PrivateMessageText = string.Empty;
  35. string PrivateMessageUserOrGroupName = string.Empty;
  36. GUIMessageList messages = new GUIMessageList();
  37. #endregion
  38. #region Unity Events
  39. void Start()
  40. {
  41. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  42. // SaveLocal a "user" cookie if we previously used the 'Enter Name' button.
  43. // The server will set this username to the new connection.
  44. if (PlayerPrefs.HasKey("userName"))
  45. CookieJar.Set(URI, new Cookie("user", PlayerPrefs.GetString("userName")));
  46. #endif
  47. signalRConnection = new Connection(URI);
  48. // to serialize the Message class, set a more advanced json encoder
  49. signalRConnection.JsonEncoder = new BestHTTP.SignalR.JsonEncoders.LitJsonEncoder();
  50. // set up event handlers
  51. signalRConnection.OnStateChanged += signalRConnection_OnStateChanged;
  52. signalRConnection.OnNonHubMessage += signalRConnection_OnGeneralMessage;
  53. // Start to connect to the server.
  54. signalRConnection.Open();
  55. }
  56. /// <summary>
  57. /// Draw the gui.
  58. /// Get input strings.
  59. /// Handle function calls.
  60. /// </summary>
  61. void OnGUI()
  62. {
  63. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  64. {
  65. GUILayout.BeginVertical();
  66. #region To Everybody
  67. GUILayout.Label("To Everybody");
  68. GUILayout.BeginHorizontal();
  69. ToEveryBodyText = GUILayout.TextField(ToEveryBodyText, GUILayout.MinWidth(100));
  70. if (GUILayout.Button("Broadcast"))
  71. Broadcast(ToEveryBodyText);
  72. if (GUILayout.Button("Broadcast (All Except Me)"))
  73. BroadcastExceptMe(ToEveryBodyText);
  74. if (GUILayout.Button("Enter Name"))
  75. EnterName(ToEveryBodyText);
  76. if (GUILayout.Button("Join Group"))
  77. JoinGroup(ToEveryBodyText);
  78. if (GUILayout.Button("Leave Group"))
  79. LeaveGroup(ToEveryBodyText);
  80. GUILayout.EndHorizontal();
  81. #endregion
  82. #region To Me
  83. GUILayout.Label("To Me");
  84. GUILayout.BeginHorizontal();
  85. ToMeText = GUILayout.TextField(ToMeText, GUILayout.MinWidth(100));
  86. if (GUILayout.Button("Send to me"))
  87. SendToMe(ToMeText);
  88. GUILayout.EndHorizontal();
  89. #endregion
  90. #region Private Message
  91. GUILayout.Label("Private Message");
  92. GUILayout.BeginHorizontal();
  93. GUILayout.Label("Message:");
  94. PrivateMessageText = GUILayout.TextField(PrivateMessageText, GUILayout.MinWidth(100));
  95. GUILayout.Label("User or Group name:");
  96. PrivateMessageUserOrGroupName = GUILayout.TextField(PrivateMessageUserOrGroupName, GUILayout.MinWidth(100));
  97. if (GUILayout.Button("Send to user"))
  98. SendToUser(PrivateMessageUserOrGroupName, PrivateMessageText);
  99. if (GUILayout.Button("Send to group"))
  100. SendToGroup(PrivateMessageUserOrGroupName, PrivateMessageText);
  101. GUILayout.EndHorizontal();
  102. #endregion
  103. GUILayout.Space(20);
  104. if (signalRConnection.State == ConnectionStates.Closed)
  105. {
  106. if (GUILayout.Button("Start Connection"))
  107. signalRConnection.Open();
  108. }
  109. else if (GUILayout.Button("Stop Connection"))
  110. signalRConnection.Close();
  111. GUILayout.Space(20);
  112. // Draw the messages
  113. GUILayout.Label("Messages");
  114. GUILayout.BeginHorizontal();
  115. GUILayout.Space(20);
  116. messages.Draw(Screen.width - 20, 0);
  117. GUILayout.EndHorizontal();
  118. GUILayout.EndVertical();
  119. });
  120. }
  121. void OnDestroy()
  122. {
  123. // Close the connection when the sample is closed
  124. signalRConnection.Close();
  125. }
  126. #endregion
  127. #region SignalR Events
  128. /// <summary>
  129. /// Handle non-hub messages
  130. /// </summary>
  131. void signalRConnection_OnGeneralMessage(Connection manager, object data)
  132. {
  133. // For now, just create a Json string from the sent data again
  134. string reencoded = BestHTTP.JSON.Json.Encode(data);
  135. // and display it
  136. messages.Add("[Server Message] " + reencoded);
  137. }
  138. void signalRConnection_OnStateChanged(Connection manager, ConnectionStates oldState, ConnectionStates newState)
  139. {
  140. // display state changes
  141. messages.Add(string.Format("[State Change] {0} => {1}", oldState.ToString(), newState.ToString()));
  142. }
  143. #endregion
  144. #region To EveryBody Functions
  145. /// <summary>
  146. /// Broadcast a message to all connected clients
  147. /// </summary>
  148. private void Broadcast(string text)
  149. {
  150. signalRConnection.Send(new { Type = MessageTypes.Broadcast, Value = text });
  151. }
  152. /// <summary>
  153. /// Broadcast a message to all connected clients, except this client
  154. /// </summary>
  155. private void BroadcastExceptMe(string text)
  156. {
  157. signalRConnection.Send(new { Type = MessageTypes.BroadcastExceptMe, Value = text });
  158. }
  159. /// <summary>
  160. /// SaveLocal a name for this connection.
  161. /// </summary>
  162. private void EnterName(string name)
  163. {
  164. signalRConnection.Send(new { Type = MessageTypes.Join, Value = name });
  165. }
  166. /// <summary>
  167. /// Join to a group
  168. /// </summary>
  169. private void JoinGroup(string groupName)
  170. {
  171. signalRConnection.Send(new { Type = MessageTypes.AddToGroup, Value = groupName });
  172. }
  173. /// <summary>
  174. /// Leave a group
  175. /// </summary>
  176. private void LeaveGroup(string groupName)
  177. {
  178. signalRConnection.Send(new { Type = MessageTypes.RemoveFromGroup, Value = groupName });
  179. }
  180. #endregion
  181. #region To Me Functions
  182. /// <summary>
  183. /// Send a message to the very same client through the server
  184. /// </summary>
  185. void SendToMe(string text)
  186. {
  187. signalRConnection.Send(new { Type = MessageTypes.Send, Value = text });
  188. }
  189. #endregion
  190. #region Private Message Functions
  191. /// <summary>
  192. /// Send a private message to a user
  193. /// </summary>
  194. void SendToUser(string userOrGroupName, string text)
  195. {
  196. signalRConnection.Send(new { Type = MessageTypes.PrivateMessage, Value = string.Format("{0}|{1}", userOrGroupName, text) });
  197. }
  198. /// <summary>
  199. /// Send a message to a group
  200. /// </summary>
  201. void SendToGroup(string userOrGroupName, string text)
  202. {
  203. signalRConnection.Send(new { Type = MessageTypes.SendToGroup, Value = string.Format("{0}|{1}", userOrGroupName, text) });
  204. }
  205. #endregion
  206. }
  207. #endif