This article will create a simple Chat application that requires almost no basic knowledge of Node.js or socket.io, making it an ideal choice for all users.

Translation: Mervyn Zhang proofread: Jin Wei

In this paper, the program is slightly changed, all implemented by ES6, while adding some notes. Due to lack of skill, please correct the mistakes in translation.

Here is the translation:

In this tutorial, we’ll create a simple chat application that requires little or no basic knowledge of Node.js or socket.io, making it an ideal choice for all users.

Introduction to the

Writing chat applications has historically been difficult using popular Web application stacks such as LAMP(PHP). It involves polling for changes to the server and logging timestamps, so writing software is much slower.

Sockets provide two-way communication between client and server, and have been the solution for building most real-time chat systems.

This means that the server can push a message to the client. The idea is that every time you send a message, the server will receive it and push it to other connected clients.

Web framework

The first goal is to create a simple HTML page that provides a form and a list of messages. We’ll do this using The Node.js Web framework Express. Make sure Node.js is installed.

Start by creating a package.json manifest file to describe the project, and it is recommended to place it in a dedicated empty directory.

Note: in my repository, I call it socket-chat-example, but I put the project in folder 01, 02… Is an expansion of the project.

{"name": "socket-chat-example", "version": "0.0.1", "description": "socket. IO app", "dependencies": {}}Copy the code

Now, to facilitate the installation of the dependencies we need (equivalent to jar packages), we will use NPM install –save:

NPM install - save [email protected]Copy the code

NPM install –save Express NPM install –save Express

Now that Express is installed, we can create an index.js file to configure our application.

const app = require('express')();
const http = require('http').Server(app);
app.get('/', (req, res) => {
  res.send('

Hello world

'); }); http.listen(3000, () => { console.log('listening on *:3000'); });Copy the code

This process is explained by the following steps:

  1. Initialize Express as a handler that can be used to provide HTTP services:app(See line 2).
  2. Defines a routing handler that is called when visiting the front page of our website.
  3. Let the HTTP service listen on port 3000.

If you run Node index.js, you’ll see something like this:

When your browser visits http://localhost:3000:

Note: My repository code listens on port 9000, so you need to visit http://localhost:9000, as follows.

Access to the HTML

So far, we’ve called res.send in index.js and passed an HTML string. But if we put our entire application’s HTML in here, it would look very confusing. Therefore, we create an index.html file and import it.

Let’s refactor our routing handler using sendFile:

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
});Copy the code

Then populate the index.html with the following:



  
    Socket.IO chat
    
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    
  
  
    
     
    Send Copy the code

    If you restart the process (by clicking Control+C and running Node Index again) and refresh the window, you will see the following page:

    Integration of the Socket. IO

    Socket.IO consists of two parts:

    • Server that integrates (or relies on)Node.js HTTP Server:socket.io
    • Client libraries loaded on the browser side:socket.io-client

    Socket. IO will automatically serve the client for us during development, so now we just need to install one module:

    npm install --save socket.ioCopy the code

    This installs the module and adds dependencies to package.json. Now we add the following to index.js:

    const app = require('express')();
    const http = require('http').Server(app);
    const io = require('socket.io')(http);
    app.get('', (req, res) => {
      res.sendfile('index.html');
    });
    io.on('connection', (socket) => {
      console.log('a user connected');
    });
    http.listen(3000, () => {
      console.log('listening on *:3000');
    });Copy the code

    Note that I initialized a new instance of socket. IO by passing HTTP (HTTP server), then listened for a connection event on sockets and logged it to the console.

    Now in index.html, add the following code snippet before :

    
    
    Copy the code

    Loading socket.io-client exposes a global IO and connects.

    Notice that when I call IO (), I don’t specify any URL because by default it tries to connect to the host hosting the page.

    If you reload the server and site now, you’ll see the console print a User Connected. Try opening multiple pages and you will see the following message:

    Each socket also fires a special Disconnect event.

    io.on('connection', (socket) => {
      console.log('a user connected');
      socket.on('disconnect', () => {
        console.log('user disconnected');
      });
    });Copy the code

    Then if you refresh the page a few times, you’ll see:

    Emitting events

    The main idea behind socket. IO is that you can accept and send any event and any data inside it that you want. Any object that can be encoded as JSON will do, and binary data is also supported.

    When the user types a message and we let the server receive it as a chat message event, the script part of index.html should look like this:

    
    
    Copy the code

    Also in index.js we print out the Chat message event:

    io.on('connection', (socket) => {
      socket.on('chat message', (msg) => {
        console.log(`message: ${msg}`);
      });
    });Copy the code

    The result should be as follows:

    radio

    Our next goal is to send events from the server to other users.

    To send events to everyone, socket. IO gives us IO. Emit:

    io.emit('some event', { for: 'everyone' });Copy the code

    If you want to send a message to everyone that does not contain a socket, we have the broadcast flag:

    io.on('connection', (socket) => {
      socket.broadcast.emit('hi');
    });Copy the code

    In this case, for the sake of simplicity, we send the message to everyone, including the sender:

    io.on('connection', (socket) => {
      socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
      });
    });
    Copy the code

    On the client side, when we capture the Chat Message event we display it on the page, with all the client-side javascript code as follows:

    Copy the code

    That’s about 20 lines of code to complete our chat program, which should look something like this:

    Homework

    Here are some ideas for improving the app:

    • Broadcast a message to the connected user when someone connects or disconnects;
    • Add support for nicknames;
    • Don’t send your own message to someone who wants to send it. Instead, as long as he pressesEnterKey to add messages directly;
    • Add the user is entering the function;
    • Show who is online;
    • Add private messages;
    • Store messages in a database;
    • Share your improvements!

    Get this example

    You can find it on Github: Original DEMO My DEMO

    Git address:

    $ git clone https://github.com/guille/chat-example.gitCopy the code

    Simple chat application based on socket. IO

    Author :Mervyn Zhang

    Published time :2017-01-04, 15:46:06

    Last updated :2017-01-04, 15:56:33

    The original link: www.foreverz.cn/2017/01/04/…

    License agreement: “Attribution – Non-commercial – Same way to share 4.0”.

    Node.js nodeGrass web page request module