Nodejs instant chat
I always wanted to create an instant chat application. I saw socket. io a few days ago. I felt pretty good. I made some modifications myself and it felt quite good. The example given on the official website is very simple. The following improvements have been made to push historical messages.
Demo address: chat.androiddevelop.cn
Server code:
Var app = require ('express ') (); var http = require ('http '). server (app); var io = require ('socket. io ') (http); var history = new Array (); app. get ('/', function (req, res) {res.sendfile('chat.html ') ;}); io. on ('connection', function (socket) {socket. on ('chat message', function (msg) {io. emit ('chat message', msg); addMsg (msg) ;}); socket. on ('login message', function (msg) {socket. join ('History room'); for (var I = 0; I
100) history. shift ();};
Chat page code:
Chat Room
<Script src = "/socket. io/socket. io. js "> </script> <script src =" http://code.jquery.com/jquery-1.11.1.js "> </script> <script> var socket = io (); var login = true; var username = ""; var myDate = new Date (); $ ('form '). submit (function () {if (login) {username = $ ('# m '). val (); if (username. length = 0) {alert ("Enter the user name"); return false;} login = false; socket. emit ('login message', "lyd _" + username + 'added to the chatting room' + myDate. getMonth () + "-" + myDate. getDate () + "" + myDate. getHours () + ":" + myDate. getMinutes () + ":" + myDate. getSeconds (); ('{btn'{.html ("send");} else {socket. emit ('chat message', username + "#" + $ ('# m '). val () ;}$ ('# m '). val (''); return false ;}); socket. on ('chat message', function (msg) {var item = msg. split ("#", 2); if (msg. indexOf ('lyd _ ') = 0) $ (' # messages '). append ('
'+ Msg. substr (5) +''); Else if (msg. indexOf (username) = 0) {$ (' # messages '). append ('
'+ Item [0] + ':'); $ (' # Messages '). append ('
'+ Item [1] +'');} Else {$ (' # messages '). append ('
'+ Item [0] + ':'); $ (' # Messages '). append ('
'+ Item [1] +'') ;}}); </Script>
In this way, a chat room is implemented. Enter the user name, log on, and the server returns the last 100 messages.