ChatSample.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using System;
  2. using System.Collections.Generic;
  3. using BestHTTP.Examples.Helpers;
  4. using BestHTTP.SocketIO3;
  5. using BestHTTP.SocketIO3.Events;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8. namespace BestHTTP.Examples.SocketIO3
  9. {
  10. #pragma warning disable 0649
  11. [PlatformSupport.IL2CPP.Preserve]
  12. class LoginData
  13. {
  14. [PlatformSupport.IL2CPP.Preserve] public int numUsers;
  15. }
  16. [PlatformSupport.IL2CPP.Preserve]
  17. sealed class NewMessageData
  18. {
  19. [PlatformSupport.IL2CPP.Preserve] public string username;
  20. [PlatformSupport.IL2CPP.Preserve] public string message;
  21. }
  22. [PlatformSupport.IL2CPP.Preserve]
  23. sealed class UserJoinedData : LoginData
  24. {
  25. [PlatformSupport.IL2CPP.Preserve] public string username;
  26. }
  27. [PlatformSupport.IL2CPP.Preserve]
  28. sealed class TypingData
  29. {
  30. [PlatformSupport.IL2CPP.Preserve] public string username;
  31. }
  32. #pragma warning restore
  33. public sealed class ChatSample : BestHTTP.Examples.Helpers.SampleBase
  34. {
  35. private readonly TimeSpan TYPING_TIMER_LENGTH = TimeSpan.FromMilliseconds(700);
  36. #pragma warning disable 0649, 0414
  37. [SerializeField]
  38. [Tooltip("The Socket.IO service address to connect to")]
  39. private string address = "https://socket-io-3-chat-5ae3v.ondigitalocean.app";
  40. [Header("Login Details")]
  41. [SerializeField]
  42. private RectTransform _loginRoot;
  43. [SerializeField]
  44. private InputField _userNameInput;
  45. [Header("Chat Setup")]
  46. [SerializeField]
  47. private RectTransform _chatRoot;
  48. [SerializeField]
  49. private Text _participantsText;
  50. [SerializeField]
  51. private ScrollRect _scrollRect;
  52. [SerializeField]
  53. private RectTransform _contentRoot;
  54. [SerializeField]
  55. private TextListItem _listItemPrefab;
  56. [SerializeField]
  57. private int _maxListItemEntries = 100;
  58. [SerializeField]
  59. private Text _typingUsersText;
  60. [SerializeField]
  61. private InputField _input;
  62. [Header("Buttons")]
  63. [SerializeField]
  64. private Button _connectButton;
  65. [SerializeField]
  66. private Button _closeButton;
  67. #pragma warning restore
  68. /// <summary>
  69. /// The Socket.IO manager instance.
  70. /// </summary>
  71. private SocketManager Manager;
  72. /// <summary>
  73. /// True if the user is currently typing
  74. /// </summary>
  75. private bool typing;
  76. /// <summary>
  77. /// When the message changed.
  78. /// </summary>
  79. private DateTime lastTypingTime = DateTime.MinValue;
  80. /// <summary>
  81. /// Users that typing.
  82. /// </summary>
  83. private List<string> typingUsers = new List<string>();
  84. #region Unity Events
  85. protected override void Start()
  86. {
  87. base.Start();
  88. this._userNameInput.text = PlayerPrefs.GetString("SocketIO3ChatSample_UserName");
  89. SetButtons(!string.IsNullOrEmpty(this._userNameInput.text), false);
  90. SetPanels(true);
  91. }
  92. void OnDestroy()
  93. {
  94. if (this.Manager != null)
  95. {
  96. // Leaving this sample, close the socket
  97. this.Manager.Close();
  98. this.Manager = null;
  99. }
  100. }
  101. public void OnUserNameInputChanged(string userName)
  102. {
  103. SetButtons(!string.IsNullOrEmpty(userName), false);
  104. }
  105. public void OnUserNameInputSubmit(string userName)
  106. {
  107. if (Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return))
  108. OnConnectButton();
  109. }
  110. public void UpdateTyping()
  111. {
  112. if (!typing)
  113. {
  114. typing = true;
  115. Manager.Socket.Emit("typing");
  116. }
  117. lastTypingTime = DateTime.UtcNow;
  118. }
  119. public void OnMessageInput(string textToSend)
  120. {
  121. if ((!Input.GetKeyDown(KeyCode.KeypadEnter) && !Input.GetKeyDown(KeyCode.Return)) || string.IsNullOrEmpty(textToSend))
  122. return;
  123. Manager.Socket.Emit("new message", textToSend);
  124. AddText(string.Format("{0}: {1}", this._userNameInput.text, textToSend));
  125. }
  126. public void OnConnectButton()
  127. {
  128. SetPanels(false);
  129. PlayerPrefs.SetString("SocketIO3ChatSample_UserName", this._userNameInput.text);
  130. AddText("Connecting...");
  131. // Create the Socket.IO manager
  132. Manager = new SocketManager(new Uri(this.address));
  133. Manager.Socket.On<ConnectResponse>(SocketIOEventTypes.Connect, OnConnected);
  134. Manager.Socket.On(SocketIOEventTypes.Disconnect, OnDisconnected);
  135. Manager.Socket.On<LoginData>("login", OnLogin);
  136. Manager.Socket.On<NewMessageData>("new message", OnNewMessage);
  137. Manager.Socket.On<UserJoinedData>("user joined", OnUserJoined);
  138. Manager.Socket.On<UserJoinedData>("user left", OnUserLeft);
  139. Manager.Socket.On<TypingData>("typing", OnTyping);
  140. Manager.Socket.On<TypingData>("stop typing", OnStopTyping);
  141. SetButtons(false, true);
  142. }
  143. public void OnCloseButton()
  144. {
  145. SetButtons(false, false);
  146. this.Manager.Close();
  147. }
  148. void Update()
  149. {
  150. if (typing)
  151. {
  152. var typingTimer = DateTime.UtcNow;
  153. var timeDiff = typingTimer - lastTypingTime;
  154. if (timeDiff >= TYPING_TIMER_LENGTH)
  155. {
  156. Manager.Socket.Emit("stop typing");
  157. typing = false;
  158. }
  159. }
  160. }
  161. #endregion
  162. #region SocketIO Events
  163. private void OnConnected(ConnectResponse resp)
  164. {
  165. AddText("Connected! Socket.IO SID: " + resp.sid);
  166. Manager.Socket.Emit("add user", this._userNameInput.text);
  167. this._input.interactable = true;
  168. }
  169. private void OnDisconnected()
  170. {
  171. AddText("Disconnected!");
  172. SetPanels(true);
  173. SetButtons(true, false);
  174. }
  175. private void OnLogin(LoginData data)
  176. {
  177. AddText("Welcome to Socket.IO Chat");
  178. if (data.numUsers == 1)
  179. this._participantsText.text = "there's 1 participant";
  180. else
  181. this._participantsText.text = "there are " + data.numUsers + " participants";
  182. }
  183. private void OnNewMessage(NewMessageData data)
  184. {
  185. AddText(string.Format("{0}: {1}", data.username, data.message));
  186. }
  187. private void OnUserJoined(UserJoinedData data)
  188. {
  189. AddText(string.Format("{0} joined", data.username));
  190. if (data.numUsers == 1)
  191. this._participantsText.text = "there's 1 participant";
  192. else
  193. this._participantsText.text = "there are " + data.numUsers + " participants";
  194. }
  195. private void OnUserLeft(UserJoinedData data)
  196. {
  197. AddText(string.Format("{0} left", data.username));
  198. if (data.numUsers == 1)
  199. this._participantsText.text = "there's 1 participant";
  200. else
  201. this._participantsText.text = "there are " + data.numUsers + " participants";
  202. }
  203. private void OnTyping(TypingData data)
  204. {
  205. int idx = typingUsers.FindIndex((name) => name.Equals(data.username));
  206. if (idx == -1)
  207. typingUsers.Add(data.username);
  208. SetTypingUsers();
  209. }
  210. private void OnStopTyping(TypingData data)
  211. {
  212. int idx = typingUsers.FindIndex((name) => name.Equals(data.username));
  213. if (idx != -1)
  214. typingUsers.RemoveAt(idx);
  215. SetTypingUsers();
  216. }
  217. #endregion
  218. private void AddText(string text)
  219. {
  220. GUIHelper.AddText(this._listItemPrefab, this._contentRoot, text, this._maxListItemEntries, this._scrollRect);
  221. }
  222. private void SetTypingUsers()
  223. {
  224. if (this.typingUsers.Count > 0)
  225. {
  226. System.Text.StringBuilder sb = new System.Text.StringBuilder(this.typingUsers[0], this.typingUsers.Count + 1);
  227. for (int i = 1; i < this.typingUsers.Count; ++i)
  228. sb.AppendFormat(", {0}", this.typingUsers[i]);
  229. if (this.typingUsers.Count == 1)
  230. sb.Append(" is typing!");
  231. else
  232. sb.Append(" are typing!");
  233. this._typingUsersText.text = sb.ToString();
  234. }
  235. else
  236. this._typingUsersText.text = string.Empty;
  237. }
  238. private void SetPanels(bool login)
  239. {
  240. if (login)
  241. {
  242. this._loginRoot.gameObject.SetActive(true);
  243. this._chatRoot.gameObject.SetActive(false);
  244. this._input.interactable = false;
  245. }
  246. else
  247. {
  248. this._loginRoot.gameObject.SetActive(false);
  249. this._chatRoot.gameObject.SetActive(true);
  250. this._input.interactable = true;
  251. }
  252. }
  253. private void SetButtons(bool connect, bool close)
  254. {
  255. if (this._connectButton != null)
  256. this._connectButton.interactable = connect;
  257. if (this._closeButton != null)
  258. this._closeButton.interactable = close;
  259. }
  260. }
  261. }