123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320 |
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Socket.IO Chat Example</title>
- <style>/* Fix user-agent */
- *{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%}
- </style>
- </head>
- <body>
- <ul class="pages">
- <li class="chat page">
- <div class="chatArea">
- <ul class="messages"></ul>
- </div>
- <input class="inputMessage" placeholder="Type here..."/>
- </li>
- <li class="login page">
- <div class="form">
- <h3 class="title">What's your nickname?</h3>
- <input class="usernameInput" type="text" maxlength="14" />
- </div>
- </li>
- </ul>
- <script src="/js/socket.io-1.2.0.js"></script>
- <script src="/js/jquery.js"></script>
- <script src="/js/rpc.js"></script>
- <script>
- //$(function() {
- var FADE_TIME = 150; // ms
- var TYPING_TIMER_LENGTH = 400; // ms
- var COLORS = [
- '#e21400', '#91580f', '#f8a700', '#f78b00',
- '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
- '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
- ];
- // Initialize varibles
- var $window = $(window);
- var $usernameInput = $('.usernameInput'); // Input for username
- var $messages = $('.messages'); // Messages area
- var $inputMessage = $('.inputMessage'); // Input message input box
- var $loginPage = $('.login.page'); // The login page
- var $chatPage = $('.chat.page'); // The chatroom page
- // Prompt for setting a username
- var username;
- var connected = false;
- var typing = false;
- var lastTypingTime;
- var $currentInput = $usernameInput.focus();
- var rpc_client = new rpc('http://'+window.location.host,{'reconnect':true});
- rpc_client.on('reconnect', function (data) {
- self.location.href = 'http://'+window.location.host;
- });
- rpc_client.on('disconnect', function (data) {
- addChatMessage({"username":"sys tips","message":"disconnect"});
- });
- rpc_client.on('connect_failed', function (data) {
- alert("connect_failed");
- });
- rpc_client.on('reconnect_failed', function (data) {
- alert("reconnect_failed");
- });
- rpc_client.on('error', function (data) {
- alert("error");
- });
- function addParticipantsMessage (data) {
- var message = '';
- if (data.numUsers === 1) {
- message += "there's 1 participant";
- } else {
- message += "there are " + data.numUsers + " participants";
- }
- log(message);
- }
- // Sets the client's username
- function setUsername () {
- username = cleanInput($.trim($usernameInput.val()));
- // If the username is valid
- if (username) {
- $loginPage.fadeOut();
- $chatPage.show();
- $loginPage.off('click');
- $currentInput = $inputMessage.focus();
- // Tell the server your username
- rpc_client.emit('adduser', username);
- }
- }
- // Sends a chat message
- function sendMessage () {
- var message = $inputMessage.val();
- // Prevent markup from being injected into the message
- message = cleanInput(message);
- // if there is a non-empty message and a socket connection
- if (message && connected) {
- $inputMessage.val('');
- addChatMessage({
- username: username,
- message: message
- });
- // tell server to execute 'new message' and send along one parameter
- rpc_client.emit('chat', message);
- }
- }
- // Log a message
- function log (message, options) {
- var $el = $('<li style="display:block"/>').addClass('log').text(message);
- addMessageElement($el, options);
- }
- // Adds the visual chat message to the message list
- function addChatMessage (data, options) {
- // Don't fade the message in if there is an 'X was typing'
- var $typingMessages = getTypingMessages(data);
- options = options || {};
- if ($typingMessages.length !== 0) {
- options.fade = false;
- $typingMessages.remove();
- }
- var $usernameDiv = $('<span class="username" />')
- .text(data.username)
- .css('color', getUsernameColor(data.username));
- var $messageBodyDiv = $('<span class="messageBody" />')
- .text(data.message);
- var typingClass = data.typing ? 'typing' : '';
- var $messageDiv = $('<li class="message"></li>')
- .data('username', data.username)
- .addClass(typingClass);
-
- addMessageElement($messageDiv, options);
- $messageDiv.append($usernameDiv);
- $messageDiv.append($messageBodyDiv);
- }
- // Adds the visual chat typing message
- function addChatTyping (data) {
- data.typing = true;
- data.message = 'is typing';
- addChatMessage(data);
- }
- // Removes the visual chat typing message
- function removeChatTyping (data) {
- getTypingMessages(data).fadeOut(function () {
- $(this).remove();
- });
- }
- // Adds a message element to the messages and scrolls to the bottom
- // el - The element to add as a message
- // options.fade - If the element should fade-in (default = true)
- // options.prepend - If the element should prepend
- // all other messages (default = false)
- function addMessageElement (el, options) {
- var $el = $(el);
- // Setup default options
- if (!options) {
- options = {};
- }
- if (typeof options.fade === 'undefined') {
- options.fade = true;
- }
- if (typeof options.prepend === 'undefined') {
- options.prepend = false;
- }
- // Apply options
- if (options.fade) {
- $el.hide().fadeIn(FADE_TIME);
- }
- if (options.prepend) {
- $messages.prepend($el);
- } else {
- $messages.append($el);
- }
- $messages[0].scrollTop = $messages[0].scrollHeight;
- }
- // Prevents input from having injected markup
- function cleanInput (input) {
- return $('<div/>').text(input).text();
- }
- // Updates the typing event
- function updateTyping () {
- if (connected) {
- if (!typing) {
- typing = true;
- rpc_client.emit('typing');
- }
- lastTypingTime = (new Date()).getTime();
- setTimeout(function () {
- var typingTimer = (new Date()).getTime();
- var timeDiff = typingTimer - lastTypingTime;
- if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
- rpc_client.emit('stoptyping');
- typing = false;
- }
- }, TYPING_TIMER_LENGTH);
- }
- }
- // Gets the 'X is typing' messages of a user
- function getTypingMessages (data) {
- return $('.typing.message').filter(function (i) {
- return $(this).data('username') === data.username;
- });
- }
- // Gets the color of a username through our hash function
- function getUsernameColor (username) {
- // Compute hash code
- var hash = 7;
- for (var i = 0; i < username.length; i++) {
- hash = username.charCodeAt(i) + (hash << 5) - hash;
- }
- // Calculate color
- var index = Math.abs(hash % COLORS.length);
- return COLORS[index];
- }
- var keydown = function (event) {
- // Auto-focus the current input when a key is typed
- if (!(event.ctrlKey || event.metaKey || event.altKey)) {
- $currentInput.focus();
- }
- // When the client hits ENTER on their keyboard
- if (event.which === 13) {
- if (username) {
- sendMessage();
- rpc_client.emit('stoptyping');
- typing = false;
- } else {
- setUsername();
- }
- }
- }
- $usernameInput.keydown(keydown);
- $inputMessage.keydown(keydown);
- // Keyboard events
- //$window.keypress(keydown);
- $inputMessage.on('input', function() {
- updateTyping();
- });
- // Click events
- // Focus input when clicking anywhere on login page
- $loginPage.click(function () {
- $currentInput.focus();
- });
- // Focus input when clicking on the message input's border
- $inputMessage.click(function () {
- $inputMessage.focus();
- });
- // Socket events
- // Whenever the server emits 'login', log the login message
- rpc_client.on('login', function (data) {
- connected = true;
- // Display the welcome message
- var message = "Welcome to Socket.IO Chat – ";
- log(message, {
- prepend: true
- });
- addParticipantsMessage(data);
- });
- // Whenever the server emits 'new message', update the chat body
- rpc_client.on('chat', function (data) {
- addChatMessage(data);
- });
- // Whenever the server emits 'user joined', log it in the chat body
- rpc_client.on('userjoin', function (data) {
- log(data.username + ' joined');
- addParticipantsMessage(data);
- });
- // Whenever the server emits 'user left', log it in the chat body
- rpc_client.on('userleft', function (data) {
- log(data.username + ' left');
- addParticipantsMessage(data);
- removeChatTyping(data);
- });
- // Whenever the server emits 'typing', show the typing message
- rpc_client.on('typing', function (data) {
- addChatTyping(data);
- });
- // Whenever the server emits 'stop typing', kill the typing message
- rpc_client.on('stoptyping', function (data) {
- removeChatTyping(data);
- });
- //});
- </script>
- </body>
- </html>
|