index.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
  10. </head>
  11. <body>
  12. <ul class="pages">
  13. <li class="chat page">
  14. <div class="chatArea">
  15. <ul class="messages"></ul>
  16. </div>
  17. <input class="inputMessage" placeholder="Type here..."/>
  18. <br />
  19. <br />
  20. <input type="button" value="发送" class="send" />
  21. </li>
  22. <li class="login page">
  23. <div class="form">
  24. <h3 class="title">What's your nickname?</h3>
  25. <input class="usernameInput" type="text" maxlength="14" />
  26. <input type="button" value="确定" class="btnOK" />
  27. </div>
  28. </li>
  29. </ul>
  30. <script src="/js/socket.io-1.2.0.js"></script>
  31. <script src="/js/jquery.js"></script>
  32. <script src="/js/rpc.js"></script>
  33. <script>
  34. function GetRequest() {
  35. var url = location.search; //获取url中"?"符后的字串
  36. var theRequest = new Object();
  37. var value = 0;
  38. if (url.indexOf("?") != -1) {
  39. var str = url.substr(1);
  40. strs = str.split("&");
  41. for(var i = 0; i < strs.length; i ++) {
  42. var arr = strs[i].split("=");
  43. var key = unescape(arr[0]);
  44. var value = unescape(arr[1]);
  45. theRequest[key] = value;
  46. }
  47. }
  48. return value;
  49. }
  50. var roomId = GetRequest();
  51. if(roomId == 0){
  52. alert('请先输入房间id,格式如:http://IP:端口?roomId=10');
  53. }
  54. //$(function() {
  55. var FADE_TIME = 150; // ms
  56. var TYPING_TIMER_LENGTH = 400; // ms
  57. var COLORS = [
  58. '#e21400', '#91580f', '#f8a700', '#f78b00',
  59. '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
  60. '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  61. ];
  62. // Initialize varibles
  63. var $window = $(window);
  64. var $usernameInput = $('.usernameInput'); // Input for username
  65. var $messages = $('.messages'); // Messages area
  66. var $inputMessage = $('.inputMessage'); // Input message input box
  67. var $loginPage = $('.login.page'); // The login page
  68. var $chatPage = $('.chat.page'); // The chatroom page
  69. // Prompt for setting a username
  70. var username;
  71. var typing = false;
  72. var lastTypingTime;
  73. var $currentInput = $usernameInput.focus();
  74. var fail_msg = {};
  75. var rpc_client = new rpcClient('http://'+window.location.host);
  76. function resendFailMsg() {
  77. console.log(fail_msg);
  78. for (var key in fail_msg) {
  79. (function(){
  80. var fmsg = fail_msg[key];
  81. var local_key = key;
  82. rpc_client.emit('chat', fmsg,{
  83. "success": function(data) {
  84. addChatMessage({"username":fmsg.username,"message":fmsg.message+" resend suc"});
  85. delete fail_msg[local_key];
  86. },
  87. "timeout_time": 4000,
  88. "timeout_cb": function() {
  89. },
  90. "error": function() {
  91. }
  92. });
  93. })();
  94. }
  95. }
  96. function addEvent() {
  97. rpc_client.setBeatTime(5000);
  98. rpc_client.on('connect', function () {
  99. if (username) {
  100. setUsername();
  101. resendFailMsg();
  102. }
  103. addChatMessage({"username":"sys tips","message":"connect"});
  104. });
  105. rpc_client.on('reconnect', function () {
  106. addChatMessage({"username":"sys tips","message":"reconnect"});
  107. });
  108. rpc_client.on('disconnect', function (data) {
  109. addChatMessage({"username":"sys tips","message":"disconnect"});
  110. });
  111. rpc_client.on('connect_error', function () {
  112. addChatMessage({"username":"sys tips","message":"connect fail"});
  113. });
  114. rpc_client.on('connect_timeout', function () {
  115. addChatMessage({"username":"sys tips","message":"connect timeout"});
  116. });
  117. rpc_client.on('error', function () {
  118. addChatMessage({"username":"sys tips","message":"error"});
  119. });
  120. // Whenever the server emits 'login', log the login message
  121. rpc_client.on('login', function (data) {
  122. connected = true;
  123. // Display the welcome message
  124. // var message = "Welcome to Socket.IO Chat – ";
  125. // log(message, {
  126. // prepend: true
  127. // });
  128. // addParticipantsMessage(data);
  129. });
  130. // Whenever the server emits 'new message', update the chat body
  131. rpc_client.on('chat', function (data, cb) {
  132. addChatMessage(data);
  133. if (cb) cb("ok");
  134. });
  135. // Whenever the server emits 'user joined', log it in the chat body
  136. rpc_client.on('userjoin', function (data) {
  137. log(data.username + ' joined');
  138. addParticipantsMessage(data);
  139. });
  140. // Whenever the server emits 'user left', log it in the chat body
  141. rpc_client.on('userleft', function (data) {
  142. log(data.username + ' left');
  143. addParticipantsMessage(data);
  144. removeChatTyping(data);
  145. });
  146. // Whenever the server emits 'typing', show the typing message
  147. rpc_client.on('typing', function (data) {
  148. addChatTyping(data);
  149. });
  150. // Whenever the server emits 'stop typing', kill the typing message
  151. rpc_client.on('stoptyping', function (data) {
  152. removeChatTyping(data);
  153. });
  154. }
  155. addEvent();
  156. function addParticipantsMessage (data) {
  157. var message = '';
  158. if (data.numUsers === 1) {
  159. message += "there's 1 participant";
  160. } else {
  161. message += "there are " + data.numUsers + " participants";
  162. }
  163. log(message);
  164. }
  165. // Sets the client's username
  166. function setUsername () {
  167. username = cleanInput($.trim($usernameInput.val()));
  168. // If the username is valid
  169. if (username) {
  170. $loginPage.fadeOut();
  171. $chatPage.show();
  172. $loginPage.off('click');
  173. $currentInput = $inputMessage.focus();
  174. // Tell the server your username
  175. rpc_client.emit('adduser', {"username":username,"roomId":roomId});
  176. }
  177. }
  178. // Sends a chat message
  179. function sendMessage () {
  180. var message = $inputMessage.val();
  181. // Prevent markup from being injected into the message
  182. message = cleanInput(message);
  183. // if there is a non-empty message and a socket connection
  184. if (message && connected) {
  185. $inputMessage.val('');
  186. var msg = {username: username,message: message,roomId:roomId};
  187. addChatMessage(msg);
  188. // tell server to execute 'new message' and send along one parameter
  189. rpc_client.emit('chat', msg,{
  190. "success": function(data) {
  191. //alert(data);
  192. },
  193. "timeout_time": 8000,
  194. "timeout_cb": function() {
  195. alert("send timeout");
  196. },
  197. "error": function() {
  198. alert("send error");
  199. }
  200. });
  201. }
  202. }
  203. // Log a message
  204. function log (message, options) {
  205. var $el = $('<li style="display:block"/>').addClass('log').text(message);
  206. addMessageElement($el, options);
  207. }
  208. // Adds the visual chat message to the message list
  209. function addChatMessage (data, options) {
  210. // Don't fade the message in if there is an 'X was typing'
  211. var $typingMessages = getTypingMessages(data);
  212. options = options || {};
  213. if ($typingMessages.length !== 0) {
  214. options.fade = false;
  215. $typingMessages.remove();
  216. }
  217. var $usernameDiv = $('<span class="username" />')
  218. .text(data.username)
  219. .css('color', getUsernameColor(data.username));
  220. var $messageBodyDiv = $('<span class="messageBody" />')
  221. .text(data.message);
  222. var typingClass = data.typing ? 'typing' : '';
  223. var $messageDiv = $('<li class="message"></li>')
  224. .data('username', data.username)
  225. .addClass(typingClass);
  226. addMessageElement($messageDiv, options);
  227. $messageDiv.append($usernameDiv);
  228. $messageDiv.append($messageBodyDiv);
  229. }
  230. // Adds the visual chat typing message
  231. function addChatTyping (data) {
  232. data.typing = true;
  233. data.message = 'is typing';
  234. addChatMessage(data);
  235. }
  236. // Removes the visual chat typing message
  237. function removeChatTyping (data) {
  238. getTypingMessages(data).fadeOut(function () {
  239. $(this).remove();
  240. });
  241. }
  242. // Adds a message element to the messages and scrolls to the bottom
  243. // el - The element to add as a message
  244. // options.fade - If the element should fade-in (default = true)
  245. // options.prepend - If the element should prepend
  246. // all other messages (default = false)
  247. function addMessageElement (el, options) {
  248. var $el = $(el);
  249. // Setup default options
  250. if (!options) {
  251. options = {};
  252. }
  253. if (typeof options.fade === 'undefined') {
  254. options.fade = true;
  255. }
  256. if (typeof options.prepend === 'undefined') {
  257. options.prepend = false;
  258. }
  259. // Apply options
  260. if (options.fade) {
  261. $el.hide().fadeIn(FADE_TIME);
  262. }
  263. if (options.prepend) {
  264. $messages.prepend($el);
  265. } else {
  266. $messages.append($el);
  267. }
  268. $messages[0].scrollTop = $messages[0].scrollHeight;
  269. }
  270. // Prevents input from having injected markup
  271. function cleanInput (input) {
  272. return $('<div/>').text(input).text();
  273. }
  274. // Updates the typing event
  275. function updateTyping () {
  276. if (connected) {
  277. if (!typing) {
  278. typing = true;
  279. rpc_client.emit('typing');
  280. }
  281. lastTypingTime = (new Date()).getTime();
  282. setTimeout(function () {
  283. var typingTimer = (new Date()).getTime();
  284. var timeDiff = typingTimer - lastTypingTime;
  285. if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
  286. rpc_client.emit('stoptyping');
  287. typing = false;
  288. }
  289. }, TYPING_TIMER_LENGTH);
  290. }
  291. }
  292. // Gets the 'X is typing' messages of a user
  293. function getTypingMessages (data) {
  294. return $('.typing.message').filter(function (i) {
  295. return $(this).data('username') === data.username;
  296. });
  297. }
  298. // Gets the color of a username through our hash function
  299. function getUsernameColor (username) {
  300. // Compute hash code
  301. var hash = 7;
  302. for (var i = 0; i < username.length; i++) {
  303. hash = username.charCodeAt(i) + (hash << 5) - hash;
  304. }
  305. // Calculate color
  306. var index = Math.abs(hash % COLORS.length);
  307. return COLORS[index];
  308. }
  309. var keydown = function (event) {
  310. // Auto-focus the current input when a key is typed
  311. if (!(event.ctrlKey || event.metaKey || event.altKey)) {
  312. $currentInput.focus();
  313. }
  314. // When the client hits ENTER on their keyboard
  315. if (event.which === 13) {
  316. if (username) {
  317. sendMessage();
  318. rpc_client.emit('stoptyping');
  319. typing = false;
  320. } else {
  321. setUsername();
  322. }
  323. }
  324. };
  325. $usernameInput.keydown(keydown);
  326. $inputMessage.keydown(keydown);
  327. // Keyboard events
  328. //$window.keypress(keydown);
  329. $inputMessage.on('input', function() {
  330. updateTyping();
  331. });
  332. // Click events
  333. // Focus input when clicking anywhere on login page
  334. $loginPage.click(function () {
  335. $currentInput.focus();
  336. });
  337. // Focus input when clicking on the message input's border
  338. $inputMessage.click(function () {
  339. $inputMessage.focus();
  340. });
  341. $(".btnOK").click(function(){
  342. if (username) {
  343. sendMessage();
  344. rpc_client.emit('stoptyping');
  345. typing = false;
  346. } else {
  347. setUsername();
  348. }
  349. });
  350. // Socket events
  351. //});
  352. </script>
  353. </body>
  354. </html>