Socket.io in node.js USES an instance

  • 2020-03-30 04:14:51
  • OfStack

1. Introduction

The first is the official website of socket.io: (link: http://socket.io)

The official website is very concise, even without API documentation, only a simple "How to use" can refer to. Because socket.io is as simple and easy to use as the official website.

2. Installation and deployment

2.1 installation

The first installation is very simple, in the node.js environment as long as one sentence:


npm install socket.io

2.2 build the server in conjunction with express

Express is a small node. js Web application framework that is often used to build HTTP servers, so take socket. IO and express as examples.


var express = require('express')
    , app = express()
    , server = require('http').createServer(app)
    , io = require('socket.io').listen(server);
server.listen(3001);

If you do not use express, refer to socket.io/#how-to-use

3. Basic usage

It is mainly divided into two pieces of code, the server side and the client side, which are very simple.

Server (app.js) :


//The contiguous code
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');}); io.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('other event', function (data) {
        console.log(data);
    });
});

First, the IO. Sockets. On function accepts the string "connection" as an event for the client to initiate a connection. When we use socket.io, we basically handle user requests in this callback function.

The two most important functions of socket are emit and on. The former submits (emits) an event (whose name is represented as a string). The event name can be customized, and there are some default event names. The latter receives an event (the event name is represented as a string), followed by a callback function that receives the event call, where data is the received data.

In the example above, we sent the news event and received the other event event, so the client should have a corresponding receive and send event. Yes, the client code is the opposite of the server, and very similar.

The Client (Client. Js)


<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost');
    socket.on('news', function (data) {
        console.log(data);
        socket.emit('other event', { my: 'data' });
    });
</script>

There are two things to note: the socket.io.js path should be written correctly. This js file is actually in the node_modules folder on the server side. Of course, you can copy the server-side socket.io.js file locally and make it a client-side js file so that you don't have to request the js file from the Node server every time, thus enhancing stability. The second is to use var socket = IO. Connect (' website address or IP '); To get the socket object, then the socket can be used to send and receive events. For event handling, the code above means that after receiving the "news" event, it prints the received data and sends the "other event" event to the server.

Note: built-in default event names such as "disconnect" indicate that the client connection has been disconnected, "message" indicates that a message has been received, and so on. Custom event names, try not to duplicate the default event names built into socket.io to avoid unnecessary trouble.

4. Other common apis

1). Broadcast to all clients: socket.broadcast. Emit ('broadcast message');

2). Getting into a room (great! Socket.join ('your room name') : socket.join('your room name')

3). Broadcast a message to a room (the sender cannot receive the message) : socket.broadcast. To ('your room name'). Emit ('broadcast room message');

4). Broadcast a message to a room (this API belongs to IO. Sockets) : IO. Sockets. In ('another room name'). Emit ('broadcast room message');

5). Force the use of WebSocket communication (client) socket.send('hi'), (server) with socket.on('message', function(data){}) to receive.

5. Use socket.io to build a chat room

Finally, we conclude this article with a simple example. Building a chat room with socket.io is about 50 lines of code, and real-time chat is very good. Key codes are posted below:

Server (socketChat. Js)


//A dictionary of client connections, when a client connects to a server,
//A unique socketId is generated, which holds the mapping of the socketId to user information (nicknames, etc.)
var connectionList = {}; exports.startChat = function (io) {
    io.sockets.on('connection', function (socket) {
        //When the client connects, save the socketId and user name
        var socketId = socket.id;
        connectionList[socketId] = {
            socket: socket
        };         //The user enters the chatroom event and broadcasts its user name
to other online users         socket.on('join', function (data) {
            socket.broadcast.emit('broadcast_join', data);
            connectionList[socketId].username = data.username;
        });         //An event in which a user leaves a chat room, broadcasting his or her departure to other online users
        socket.on('disconnect', function () {
            if (connectionList[socketId].username) {
                socket.broadcast.emit('broadcast_quit', {
                    username: connectionList[socketId].username
                });
            }
            delete connectionList[socketId];
        });         //
user speak event, broadcast to other online users         socket.on('say', function (data) {
            socket.broadcast.emit('broadcast_say',{
                username: connectionList[socketId].username,
                text: data.text
            });
        });
    })
};

The Client (socketChatClient. Js)


var socket = io.connect('http://localhost');
//Once you've connected to the server, submit an "join" event and tell someone your user name socket.emit('join', {
    username: 'Username hehe'
}); //After receiving the chat room broadcast, the message
is displayed socket.on('broadcast_join', function (data) {
    console.log(data.username + ' Joined the chat room ');
}); //After receiving the outgoing chat room broadcast, the message
is displayed socket.on('broadcast_quit', function(data) {
    console.log(data.username + ' Left the chat room ');
}); //After receiving a message sent by someone else, the message
is displayed socket.on('broadcast_say', function(data) {
    console.log(data.username + ' said : ' + data.text);
}); //Let's say we have a textarea and a send button. Btn-send
//Use jQuery to bind events
$('.btn-send').click(function(e) {
    //Gets the text of the text box
    var text = $('textarea').val();
    //When a say event is submitted, the server receives it and broadcasts
    socket.emit('say', {
        username: 'Username hehe'
        text: text
    });
});

This is a simple chat room DEMO that you can expand to suit your needs. Socket.io is basically the submission and reception of various events, the idea is very simple.


Related articles: