ConnectionAPISample.cs 8.3 KB

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