This is not a project but an example of learning for someone who has just started learning. The main implementation of the following basic functions:
1: Group chat. Everyone can receive messages from others and be able to send messages to others, each identified by an IP address.
2: Displays the current online user.
3: Log in and out for each user. Everyone else can see.
4: Each user can see if another person is entering a message.
The implementation method does not choose the inefficient polling method, but adopts the Socket.io module based on the WebSocket protocol, and the WebSocket protocol agrees to establish a full-duplex communication channel between the client and the server. So the server can actively push messages to the client. Compared to traditional polling, real-time is better.
Front-end code such as the following:
<!doctype html>
Service-Side code:/** * Created by Luzhen on 14-11-10. */var Express = require (' Express '); var app=express (); var http = require (' http '). Server (APP), var io = require (' Socket.io ') (HTTP), Var ips={};app.use (express.static (__dirname + '/public ')), App.get ('/ ', function (req, res) {res.sendfile (__dirname + '/index.html ');}); var onlinenum=0;io.on (' Connection ', function (socket) {console.log (socket.request.connection.remoteAddress); Ips[socket.request.connection.remoteaddress]=socket.request.connection.remoteaddress;//clientip// Socket.handshake.address service-side IP onlinenum++; Socket.broadcast.emit (' join ', {' IP ': socket.request.connection.remoteAddress});//Broadcast New user added Io.emit (' online num ', Onlinenum)///broadcast current online number Socket.on (' Chat message ', function (msg) {io.emit (' chat message ', {Ip:socket.request.conn ection.remoteaddress, ' content ': msg}); Console.log (' message: ' + msg); }); Socket.on (' Typing ', function (msg) {socket.broadcast.emit (' typing ', {' IP ': socket.request.connection.Remoteaddress}); }); Socket.on (' Stop typing ', function (msg) {socket.broadcast.emit (' stop typing ', {' IP ': Socket.request.connection.remo Teaddress}); }); Socket.on (' Disconnect ', function () {delete ips[socket.request.connection.remoteaddress]; onlinenum--; Socket.broadcast.emit (' user left ', {' IP ': socket.request.connection.remoteAddress, ' Onlinenum ': Onlinenum}); });}); Http.listen (The function () {Console.log (' listening on *:3000 ');});
Added anti-swipe feature, full code open source on GitHub.
Demo Demo View Effects
Nodejs now online Group chat