The use of socket.io in express framework and simple html page example

The use of socket.io in the express framework and html examples

Today I will write an article about how to use sockets in the express framework. I will also make a simple html page as a demonstration. Later, I will use the space to write an article on the front-end scaffolding such as vue. First, let’s talk about what sockets are and why they are used
. Use socket?
Socket.io is a real-time, event-based two-way communication library that enables persistent connections between clients and servers. When using Socket.io, the corresponding Socket.io library needs to be introduced on both the server side and the client side.
For Express servers, you can introduce Socket.io on the server side and use it with Express. In this way, the Express server can handle Socket.io related requests. After creating a Socket.io instance on the server side, you can attach it to a running Express server so that Socket.io and Express share the same server port.
When the client loads a web page, it can obtain the Socket.io.js file under the service port from the server. This is because Socket.io automatically provides some JavaScript files required by the client on the server side, such as Socket.io.js. By introducing this file on the client, the client can connect to the Socket.io server and conduct real-time two-way communication with the server.
In short, Socket.io provides a convenient way to establish a persistent connection between a client and a server, with real-time two-way communication via events. Using Socket.io in the Express server allows the client to connect and communicate by loading the Socket.io.js file under the service port.
It can be clearly seen from the above that in fact, most sockets are used for chat functions. After all, this function is suitable for use.
How to use socket.io with express
First of all, we know that the framework generated by express scaffolding, the started server is in www under bin, and socket needs to use server, so just add the socket code under www, but you must develop good coding habits , after all, the requirement of the www file is to be concise and easy to maintain, so we need to create a socketio file in any directory or root directory (I found that the words in the project were wrongly written, please don't mind, of course don't follow me ~ ) , As shown below:
Look at the last file, which is newly created.
The newly created file is
(scoketio)
, and then the two packages are downloaded first. The command is:

npm install socket.io
npm install cors //这个是后面可能会遇到的跨域问题,反正先下了

After finishing it, there was no problem. After that, I started editing the content of the Scoketio page. The idea was to create a socket example and then expose the method:

var scoketio={
    
    }  //要暴露出去的对象 
var scoket_io=require('socket.io')
var cors=require('cors')
scoketio.getscoketio=function(server)
{
    
    
    var io=scoket_io(server,{
    
    cors:true});   //server就是服务器监听的对象
    io.listen(1234)     //这里我将重新给一个端口
    io.on('connection',function(socket)  //监听connect行为,传入一个socket对象
    {
    
    
        console.log('a user has join');
        socket.on('message',function(obj)   //监听message行为,也就是用户发信息的行为
        {
    
    
            io.emit('message',obj)  //io向所有用户的窗口广播该socket对象的信息
            console.log(obj.userid+'说:'+obj.content);//控制台输出谁说了什么
        })
    })
}

module.exports=scoketio;

There are a lot of details, so I will give the whole code first, and then explain it bit by bit , and then how to reference this page in www. First, introduce the page I just wrote at the beginning, and behind the server where the app object has been mounted, Use the exposed getsocketio method to pass server as a parameter to io:

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myexpressjsj:server');
var http = require('http');
var io=require('../scoketio')  //这个

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
io.getscoketio(server)  //这个

Next, let’s write a simple html5 page and test whether the interface can be used:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <title>xjd的聊天室</title>
</head>
<body>
    <script>
        this.socket=io.connect('ws://localhost:3000')  //与刚刚的服务区建立连接,使用的是wx协议
        this.user={
    
    
            username:'xjd',
            userid:Date.now()
        }
        this.socket.on('message',function(obj)  //监听message行为,会触发里面的function
        {
    
       
            console.log(obj);
        })
    </script>
</body>
</html>

There are some details that I have to talk about. First of all, we can understand io as a large object that includes all socket users. Through the emit method, the selected behavior can be triggered to all users, such as the message behavior above, but this behavior is on the front end. Defined, that is to say, trigger the message method monitored by all user pages on the front end. For example, we now start the express server.

npm run start

Then open two windows in the browser, the URLs are both localhost:3000/index.html, a blank page is normal, open the console (F12 key), and then open the server terminal, you will see two lines a user has join, which is normal :
Backstage
Then enter this.user in the console to determine the IDs of the two windows:
userid
Next, test this message, use this.socket.emit('message',{...this.user,content:'zsy I love you'}) , you will see this information in the two windows synchronized console.log():

Insert image description here

so. To explain why, by triggering the message method, the server is listening to this method. The code is:

socket.on('message',function(obj)
        {
    
    
            io.emit('message',obj)
            console.log(obj.userid+'说:'+obj.content);
        })

Therefore, when opening the server terminal, the following sentence will appear:
Insert image description here
At the same time, due to the monitoring of the server, the emit method of io is used to trigger the message behavior to all socket users. When the front-end monitors the message, all users will trigger the following code:

this.socket.on('message',function(obj)
        {
    
       
            console.log(obj);
        })

That's why the above window phenomenon appears, so when you need to add more behaviors in the future, you only need to follow the same idea. Then if you want to trigger a message for a specific user, you need to follow the io with a socket id. To identify, and then emit, you can check the official website for specific methods.
So that’s it for today’s article, it’s the first time I’ve written such a long blog by hand!

Guess you like

Origin blog.csdn.net/weixin_51295863/article/details/131670009