index.html.bak 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Socket.IO Chat Example</title>
  6. <style>/* Fix user-agent */
  7. *{box-sizing:border-box}html{font-family:"HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-weight:300;-webkit-font-smoothing:antialiased}html,body{height:100%;margin:0;padding:0}ul{list-style:none}.pages{height:100%;margin:0;padding:0;width:100%}.page{height:100%;position:absolute;width:100%}.login.page{background-color:#000}.login.page .form{height:100px;margin-top:-100px;position:absolute;text-align:center;top:50%;width:100%}.login.page .form .usernameInput{background-color:transparent;border:0;border-bottom:2px solid #fff;outline:0;padding-bottom:15px;text-align:center;width:400px}.login.page .title{font-size:200%}.login.page .usernameInput{font-size:200%;letter-spacing:3px}.login.page .title,.login.page .usernameInput{color:#fff;font-weight:100}.chat.page{display:none}.messages{font-size:150%}.inputMessage{font-size:100%}.log{color:gray;font-size:70%;margin:5px;text-align:center}.chatArea{height:100%;padding-bottom:60px}.messages{height:100%;margin:0;overflow-y:scroll;padding:10px 20px 10px 20px}.message.typing .messageBody{color:gray}.username{float:left;font-weight:700;overflow:hidden;padding-right:15px;text-align:right}.inputMessage{border:10px solid #000;bottom:0;height:60px;left:0;outline:0;padding-left:10px;position:absolute;right:0;width:100%}
  8. </style>
  9. </head>
  10. <body>
  11. <ul class="pages">
  12. <li class="chat page">
  13. <div class="chatArea">
  14. <ul class="messages"></ul>
  15. </div>
  16. <input class="inputMessage" placeholder="Type here..."/>
  17. </li>
  18. <li class="login page">
  19. <div class="form">
  20. <h3 class="title">What's your nickname?</h3>
  21. <input class="usernameInput" type="text" maxlength="14" />
  22. </div>
  23. </li>
  24. </ul>
  25. <script src="/js/socket.io-1.2.0.js"></script>
  26. <script src="/js/jquery.js"></script>
  27. <script src="/js/rpc.js"></script>
  28. <script>
  29. //$(function() {
  30. var FADE_TIME = 150; // ms
  31. var TYPING_TIMER_LENGTH = 400; // ms
  32. var COLORS = [
  33. '#e21400', '#91580f', '#f8a700', '#f78b00',
  34. '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
  35. '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  36. ];
  37. // Initialize varibles
  38. var $window = $(window);
  39. var $usernameInput = $('.usernameInput'); // Input for username
  40. var $messages = $('.messages'); // Messages area
  41. var $inputMessage = $('.inputMessage'); // Input message input box
  42. var $loginPage = $('.login.page'); // The login page
  43. var $chatPage = $('.chat.page'); // The chatroom page
  44. // Prompt for setting a username
  45. var username;
  46. var connected = false;
  47. var typing = false;
  48. var lastTypingTime;
  49. var $currentInput = $usernameInput.focus();
  50. var rpc_client = new rpc('http://'+window.location.host,{'reconnect':true});
  51. rpc_client.on('reconnect', function (data) {
  52. self.location.href = 'http://'+window.location.host;
  53. });
  54. rpc_client.on('disconnect', function (data) {
  55. addChatMessage({"username":"sys tips","message":"disconnect"});
  56. });
  57. rpc_client.on('connect_failed', function (data) {
  58. alert("connect_failed");
  59. });
  60. rpc_client.on('reconnect_failed', function (data) {
  61. alert("reconnect_failed");
  62. });
  63. rpc_client.on('error', function (data) {
  64. alert("error");
  65. });
  66. function addParticipantsMessage (data) {
  67. var message = '';
  68. if (data.numUsers === 1) {
  69. message += "there's 1 participant";
  70. } else {
  71. message += "there are " + data.numUsers + " participants";
  72. }
  73. log(message);
  74. }
  75. // Sets the client's username
  76. function setUsername () {
  77. username = cleanInput($.trim($usernameInput.val()));
  78. // If the username is valid
  79. if (username) {
  80. $loginPage.fadeOut();
  81. $chatPage.show();
  82. $loginPage.off('click');
  83. $currentInput = $inputMessage.focus();
  84. // Tell the server your username
  85. rpc_client.emit('adduser', username);
  86. }
  87. }
  88. // Sends a chat message
  89. function sendMessage () {
  90. var message = $inputMessage.val();
  91. // Prevent markup from being injected into the message
  92. message = cleanInput(message);
  93. // if there is a non-empty message and a socket connection
  94. if (message && connected) {
  95. $inputMessage.val('');
  96. addChatMessage({
  97. username: username,
  98. message: message
  99. });
  100. // tell server to execute 'new message' and send along one parameter
  101. rpc_client.emit('chat', message);
  102. }
  103. }
  104. // Log a message
  105. function log (message, options) {
  106. var $el = $('<li style="display:block"/>').addClass('log').text(message);
  107. addMessageElement($el, options);
  108. }
  109. // Adds the visual chat message to the message list
  110. function addChatMessage (data, options) {
  111. // Don't fade the message in if there is an 'X was typing'
  112. var $typingMessages = getTypingMessages(data);
  113. options = options || {};
  114. if ($typingMessages.length !== 0) {
  115. options.fade = false;
  116. $typingMessages.remove();
  117. }
  118. var $usernameDiv = $('<span class="username" />')
  119. .text(data.username)
  120. .css('color', getUsernameColor(data.username));
  121. var $messageBodyDiv = $('<span class="messageBody" />')
  122. .text(data.message);
  123. var typingClass = data.typing ? 'typing' : '';
  124. var $messageDiv = $('<li class="message"></li>')
  125. .data('username', data.username)
  126. .addClass(typingClass);
  127. addMessageElement($messageDiv, options);
  128. $messageDiv.append($usernameDiv);
  129. $messageDiv.append($messageBodyDiv);
  130. }
  131. // Adds the visual chat typing message
  132. function addChatTyping (data) {
  133. data.typing = true;
  134. data.message = 'is typing';
  135. addChatMessage(data);
  136. }
  137. // Removes the visual chat typing message
  138. function removeChatTyping (data) {
  139. getTypingMessages(data).fadeOut(function () {
  140. $(this).remove();
  141. });
  142. }
  143. // Adds a message element to the messages and scrolls to the bottom
  144. // el - The element to add as a message
  145. // options.fade - If the element should fade-in (default = true)
  146. // options.prepend - If the element should prepend
  147. // all other messages (default = false)
  148. function addMessageElement (el, options) {
  149. var $el = $(el);
  150. // Setup default options
  151. if (!options) {
  152. options = {};
  153. }
  154. if (typeof options.fade === 'undefined') {
  155. options.fade = true;
  156. }
  157. if (typeof options.prepend === 'undefined') {
  158. options.prepend = false;
  159. }
  160. // Apply options
  161. if (options.fade) {
  162. $el.hide().fadeIn(FADE_TIME);
  163. }
  164. if (options.prepend) {
  165. $messages.prepend($el);
  166. } else {
  167. $messages.append($el);
  168. }
  169. $messages[0].scrollTop = $messages[0].scrollHeight;
  170. }
  171. // Prevents input from having injected markup
  172. function cleanInput (input) {
  173. return $('<div/>').text(input).text();
  174. }
  175. // Updates the typing event
  176. function updateTyping () {
  177. if (connected) {
  178. if (!typing) {
  179. typing = true;
  180. rpc_client.emit('typing');
  181. }
  182. lastTypingTime = (new Date()).getTime();
  183. setTimeout(function () {
  184. var typingTimer = (new Date()).getTime();
  185. var timeDiff = typingTimer - lastTypingTime;
  186. if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
  187. rpc_client.emit('stoptyping');
  188. typing = false;
  189. }
  190. }, TYPING_TIMER_LENGTH);
  191. }
  192. }
  193. // Gets the 'X is typing' messages of a user
  194. function getTypingMessages (data) {
  195. return $('.typing.message').filter(function (i) {
  196. return $(this).data('username') === data.username;
  197. });
  198. }
  199. // Gets the color of a username through our hash function
  200. function getUsernameColor (username) {
  201. // Compute hash code
  202. var hash = 7;
  203. for (var i = 0; i < username.length; i++) {
  204. hash = username.charCodeAt(i) + (hash << 5) - hash;
  205. }
  206. // Calculate color
  207. var index = Math.abs(hash % COLORS.length);
  208. return COLORS[index];
  209. }
  210. var keydown = function (event) {
  211. // Auto-focus the current input when a key is typed
  212. if (!(event.ctrlKey || event.metaKey || event.altKey)) {
  213. $currentInput.focus();
  214. }
  215. // When the client hits ENTER on their keyboard
  216. if (event.which === 13) {
  217. if (username) {
  218. sendMessage();
  219. rpc_client.emit('stoptyping');
  220. typing = false;
  221. } else {
  222. setUsername();
  223. }
  224. }
  225. }
  226. $usernameInput.keydown(keydown);
  227. $inputMessage.keydown(keydown);
  228. // Keyboard events
  229. //$window.keypress(keydown);
  230. $inputMessage.on('input', function() {
  231. updateTyping();
  232. });
  233. // Click events
  234. // Focus input when clicking anywhere on login page
  235. $loginPage.click(function () {
  236. $currentInput.focus();
  237. });
  238. // Focus input when clicking on the message input's border
  239. $inputMessage.click(function () {
  240. $inputMessage.focus();
  241. });
  242. // Socket events
  243. // Whenever the server emits 'login', log the login message
  244. rpc_client.on('login', function (data) {
  245. connected = true;
  246. // Display the welcome message
  247. var message = "Welcome to Socket.IO Chat – ";
  248. log(message, {
  249. prepend: true
  250. });
  251. addParticipantsMessage(data);
  252. });
  253. // Whenever the server emits 'new message', update the chat body
  254. rpc_client.on('chat', function (data) {
  255. addChatMessage(data);
  256. });
  257. // Whenever the server emits 'user joined', log it in the chat body
  258. rpc_client.on('userjoin', function (data) {
  259. log(data.username + ' joined');
  260. addParticipantsMessage(data);
  261. });
  262. // Whenever the server emits 'user left', log it in the chat body
  263. rpc_client.on('userleft', function (data) {
  264. log(data.username + ' left');
  265. addParticipantsMessage(data);
  266. removeChatTyping(data);
  267. });
  268. // Whenever the server emits 'typing', show the typing message
  269. rpc_client.on('typing', function (data) {
  270. addChatTyping(data);
  271. });
  272. // Whenever the server emits 'stop typing', kill the typing message
  273. rpc_client.on('stoptyping', function (data) {
  274. removeChatTyping(data);
  275. });
  276. //});
  277. </script>
  278. </body>
  279. </html>