Play Node.js (d)-Build a simple chat room code _node.js

Source: Internet
Author: User
Tags emit readfile sendmsg socket jquery library

Nodejs for a long time did not follow up, recently want to use it to engage in a chat room, and then ran into the Socket.io this dongdong, said it can be used to simply realize real-time two-way event-based communication mechanism. I saw a few tutorials and used it to build a super simple chat room.

Initializing a project

Create a new folder on your computer, called "Chatroom," and then use NPM for initialization:

$ NPM Init

Then according to the prompts and related information step-by-step input, of course, you can also go down the road, after the project will generate a Package.json file, which information as follows:

$ cat Package.json
{
 "name": "Chatroom",
 "version": "1.0.0",
 "description": "A room which lets people Chat ",
 main": "Index.js",
 "scripts": {
  "test": "Nothing"
 },
 "author": "Voidy",
 " License ": ISC",
 }

This file describes the relevant information about the project.

Install Socket.io

Next, install Socket.io:

 $ NPM Install Socket.io--save

When installing the Socket.io, the--save parameter is used to save the module dependency information to the Package.json file, and when the installation is finished, the Package.json file will see that there is one more content:

 "Dependencies": {
   "Socket.io": "^1.2.1"
 }

The Socket.io is also installed under the Node_modules folder.

Implementation Chat-server side

First we write the server-side program, the new file "Index.js", in which to import the following modules:

 var http = require (' http ');      
 var socketio = require (' Socket.io '); 
 

The first line is to import the HTTP module, which we have already seen before to create the HTTP server.

The second line is to import Socket.io module, to achieve real-time chat necessary, no longer repeat.

The third line is the import FS module, which is used to read files. You'll learn about it in a specific minute.

Using the HTTP module to create the app, add the following statement to the code just now:

var app = Http.createserver (function (req, res) {
 
  fs.readfile (__dirname + '/index.html ', function (err, data) {
    if (ERR) {
      res.writehead ();
      Return Res.end (' Error loading index.html ');
    }
    Res.writehead (); 
    Res.write (data);  
    Res.end ();
  })
. Listen (8888);

The Fs.readfile () method reads the file, where it reads the index.html file, which is a presentation page for the front-end chat room that is about to be written.

Line 8th returns the status code of the request, and line 9th returns the content read to the browser. This HTTP server then uses the Listen method to listen for port 8888.

The next step is to use Socket.io to implement the chat event. The Socket.io object is then created under the HTTP server for the Index.js file just now.

var io = socketio (APP);

Then listen for the connection event, which triggers the event when the browser connects to the Socket.io service:

Io.on (' Connection ', function (socket) {
  //Monitor browser-side chat event
  socket.on (' Chat ', function (data) {
    Console.log ( data);
    Io.emit (' sendmsg ', data); 
  });

Line 4th is used to enter the information into the background of the monitor, line 5th to send the content to the client, in order to know whether the server started, I added the following sentence:

Console.log ("Server is running at http://localhost:8888")

At this point, the server-side encoding is complete.

Implementation Chat-Client

First implement the interface section, only the display of message logging and message send box, the code is as follows:

 

Then you need to add JS inside to achieve communication with the server side, the server-side data to be displayed to the client, the main code is as follows:

<script>
//Connect to Socket.io server
var socket = Io.connect ();

$ (function () {
 //Bind send button Send Message event
  $ (' #send '). On (' click ', Function () {
    var data = $ (' #m '). Val ();
   Create a chat event and send a message to the server
    //Emit (' event ') to indicate that an event command///////(' event ') was sent to
    receive information about the corresponding Event///
    So the client server side needs to use Socket.on (' chat ') to receive chat information
    socket.emit (' chat ', {msg:data});
    $ (' #m '). Val (');
  });
};

$ (function () {
  ///Receive message and display to message record box
  socket.on (' sendmsg ', function (msg) {
    $ (' #messages '). Append (' < Li> '). Text (msg.msg);
  }
); </script>

At this point, you can perform:

$ node Index.js

Then open the localhost:8888 view effect in the browser.

At this point, a simple chat room has been realized, interested friends can be extended on this basis to achieve more complex functions of the chat room.

Project source code: Source Download

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.