AngularJS + Node. js implement online chat room _ AngularJS

Source: Internet
Author: User
With the development of the Internet and information technology, how to quickly build an efficient and powerful dynamic website has become a hot topic for many researchers. This article will combine AngularJS and Node. js to build an online chat room, reflecting the advantages of AngularJs and Node. js integration. I have to say that it is much harder to get started with AngularJS than I think. After reading the PhoneCat example provided on the official website, I ran to MOOC to read the AngularJS practice series of desert and poor autumn, there are still many unclear questions about the basic usage, so I decided to make an online chat room for help. DEMO can stamp → chat room, code can stamp → ChatRoom-AngularJS.

Clear graph can stamp http://files.jb51.net/file_images/article/201508/201508281040051.gif

Function

Before proceeding with development, first clarify the functions to be implemented:

New User Login, broadcast notifications to other users
The User goes offline and broadcasts notifications to other users.
Displays online users and lists
Group chat and private message
If a user sends a group message, broadcast the message to all other users.
If the user sends a private message, the recipient interface is notified separately.

Because I am an aesthetic scum, I rely on bootstrap. In addition, I also imitated the Bubble Design in the chat record.

The page consists of two tabs: online list and chat content.

In the online list on the left, click different items to switch the chat objects in the right section.

The dialog record with the current chat object is displayed on the right, but only the last 30 records are displayed. Each chat record contains the sender's nickname and Avatar, sending time, and message content. For the Avatar, here we will make a simple process and replace it with blocks filled with random colors. In addition, the style of the sent message is naturally different from that of the received message. All the effects can be viewed.

Clear graph can stamp http://files.jb51.net/file_images/article/201508/201508281040052.png

Server

We use Node. js and express and socket. io to develop the server. Open the terminal in the program root directory and execute:

The Code is as follows:

npm init

Generate a package. json file as prompted. Enable and configure dependencies:

 "dependencies": {  "express": "^4.13.3",  "socket.io": "^1.3.6" }

Then run npm install to install the dependency module.

Next, create app. js in the root directory and write the Server code. Create a public folder to store the client code.

The main content of app. js is as follows:

Var express = require ('express '); var app = require ('express') (); var http = require ('http '). createServer (app); var io = require ('socket. io ') (http); app. use (express. static (_ dirname + '/public'); app. get ('/', function (req, res) {res.sendfile('index.html ') ;}); io. on ('connection', function (socket) {socket. on ('adduser', function (data) {// a new user enters the chat room}); socket. on ('addmessage', function (data) {// a user sends a new message}); socket. on ('disconnect', function () {// a user exits from the chat room);}); http. listen (3002, function () {console. log ('listening on *: 100 ');});

In the above Code, we added a listener for the following events:

-AddUser: a new user enters the chat room.

This event is triggered by a nickname entered by the client. After receiving the nickname, the server determines whether the nickname already exists. If the nickname already exists, the notification client's nickname is invalid:

The Code is as follows:

socket.emit('userAddingResult',{result:false});

Otherwise, notify the client that the nickname is valid and all currently connected user information, and broadcast the new user information to other connected users:

Socket. emit ('useraddingresult', {result: true}); allUsers. push (data); // allUsers saves all user sockets. emit ('alluser', allUsers); // send all online users to the new user socket. broadcast. emit ('useradded', data); // broadcast to welcome new users.

Note the differences between 'socket. emit' and 'socket. broadcast. emit'. You can view the socket. io emit usage instructions in this blog post:

// send to current request socket clientsocket.emit('message', "this is a test");// sending to all clients except sendersocket.broadcast.emit('message', "this is a test");

-AddMessage: a user sends a new message.

In this event listener, there are two types of situation processing:

1. Private Message
If the message is sent to user A, you need to obtain the socket instance corresponding to user A and then call its emit method. Therefore, when a client connects to the Server, we need to save its socket instance for future use.

The Code is as follows:

ConnectedSockets [nickname] = socket; // use a nickname as the subscript to save each socket instance. To send a private message, use

To send a private message, retrieve the socket instance and perform the following operations:

The Code is as follows:

connectedSockets[nickname].emit('messageAdded',data)

2. mass mailing
Group Sending is relatively simple. You can use the broadcast method:

The Code is as follows:

Socket. broadcast. emit ('messageadded', data); // broadcast the message, which can be seen except the original sender.

-Disconnect: A User exits from the chat room.
Three things need to be done:

1. notify other users to "deprecate a user"

The Code is as follows:

socket.broadcast.emit('userRemoved', data);

2. Remove the user from the array where all users are saved

3. Remove the socket instance from the array where all client socket instances are saved.

The Code is as follows:

Delete connectedSockets [nickname]; // delete the corresponding socket instance

Run the server code to check whether there are any errors:

The Code is as follows:

node app.js

If there is no problem, continue to write the client code.

Client

Create 'index.html 'in the publicdirectory. The client needs to use bootstrap, angularjs, socket. io, jQuery, and our own js and css files. First, introduce these files with tags.

  
     
   
   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.