socket.io solves browser compatibility (WebSocket)

         In the previous article , I talked about the ws library, one of the most popular WebSocket libraries on npm, so this article will talk about another one, which is the socket.io library. Socket.io is actually a compatible solution. When the browser does not support H5 Under the circumstances, the WebSocket mentioned in the previous article cannot be used, and other solutions can only be used. socket.io solves the compatibility of browsers.

Node implements Socket communication    |    WebSocket communication - browser native support

        Socket.io library address:   Socket.IO 

Let's use the socket.io library to realize the communication between the server and the client:

Introducing Socket.io

         Open the CMD command window and switch to the directory to be determined, and use the following command to install the socket.io library;

npm i socket.io

After the installation is complete, you only need to find a socket.io.js file from node_modules, the path is as follows: (will be used later)

/node_modules/socket.io/client-dist/socket.io.js

—— client

        The client interface here still uses the html file used earlier, and uses the script tag to import socket.ios.js to connect with the server interface; here, in order not to confuse it with the html file, separate it and use the script tag introduce;

SocketIO.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./socket.io.js" type="text/javascript"></script>
    <script src="./SocketIOClient.js"></script>
    <style>
        .chatroom{
            height: 400px;
            width: 220px;
            border: 1px solid blue;
            padding: 5px;
            overflow: scroll;
        }
        .footer{
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h3>Socket.IO 客户端</h3>
    <div id="chatroom" class="chatroom"></div>
    <div class="footer">
        <input type="text" name="sayinput" id="sayinput" value="" />
        <input type="button" name="send" id="sendbutton" value="发送" />
    </div>
</body>
</html>

SocketIOClient.js file - access to the server

var iosocket = null
window.onload = function () {
    // 连接
    iosocket = io.connect('http://127.0.0.1:9000')
    iosocket.on('connect',function(){
        iosocket.send('— — 已上线 — —')
    }) 
    // 收集
    iosocket.on('message',function(message){
        var chatroom = document.querySelector('#chatroom');
        chatroom.innerHTML += '<br/>' + message
    })
    // 关闭
    iosocket.on('disconnect',function(){
        console.log('服务器关闭');
    })
    // 发送
    function send(){
        iosocket.send(sayinput.value)
        sayinput.value = ''
    }
    // 回车
    document.onkeyup = function (event) {
        if (event.key = '13'){
            send()
        }
    }
    // 按钮
    sendbutton.onclick = function () {
        send()
    }
}

        There is not much difference between the content and some operations of WebSocket mentioned earlier, so I won’t go into details here!

-- Server

Install the express framework

Introduce socket.io 

var socket = require('socket.io')
// 服务端
// var app = require('express')()
var express = require('express')
var app = express()
var http = require('http').Server(app)
// var socket = require('socket.io')
// var io = socket(http)
var io = require('socket.io')(http)
var fs = require('fs');

app.get('/', function (req, res) {
  function callback(data) {
    res.send(data.toString())
  }
  fs.readFile('./SocketIo.html', function (err, data) {
    if (err) {
      console.log(err);
      callback('文件不存在')
    } else {
      callback(data)
    }
  })
})

// socket.io设置
// 在线用户
var onlineUsers = {}

var i = 0

io.on('connection', function (socket) {
  console.log('有人连上来了~');
  //监听新用户的加入
  socket.name = '用户' + ++i
  onlineUsers[socket.name] = socket

  // 监听用户退出
  socket.on('disconnect', function () {
    console.log('有人退出');
    delete onlineUsers[socket.name]
  })

  // 监听用户发布聊天内容
  socket.on('message', function (msg) {
    broadcast(msg, socket)
  })
})

function broadcast(msg, socket) {
  for (var key in onlineUsers) {
    onlineUsers[key].send(socket.name + ' : ' + msg)
  }
}

http.listen(9000, function () {
  console.log('Port:9000 | Running ...');
})

        What is the problem with the above writing, let's test it:

         The server is running normally, let’s take a look at the client, and access http://127.0.0.1:9000 through the browser, and the client’s web page HTML file (./SocketIO.html) will appear;

        You can use static resources for hosting, that is, create a public folder, place the managed files under this folder, and use the following command:

app.use(express.static('public'))

         Or you can also set up app.get('/...') to access like this:

app.get('/SocketIOClient.js',function(req,res){
  fs.readFile('./public/SocketIOClient.js',(err,data)=>{
    res.send(data)
  })
})
app.get('/socket.io.js',function(req,res){
  fs.readFile('./public/socket.io.js',(err,data)=>{
    res.send(data)
  })
})

script标签
    <script src="./socket.io.js" type="text/javascript"></script>
    <script src="./SocketIOClient.js"></script>

        What needs to be noted here is the request path of this script. I have talked about static resource hosting before. You can go back and read the story. Let’s test it:

        Then start a client to make user 2 go online:         

         To send information separately:

        The above is the whole content of this article, thank you for your support! If there is a complete code attached at the end that you don’t understand, it should be noted that the corresponding dependent packages need to be downloaded by yourself, express and socket.io:

// var app = require('express')()
var express = require('express')
var app = express()
// var http = require('http')
// var server = http.Server(app) 
var server = require('http').Server(app)
// var socket = require('socket.io')
// var io = socket(http)
var io = require('socket.io')(server)
var fs = require('fs');

// app.use(express.static('public'))

app.get('/', function (req, res) {
  function callback(data) {
    res.send(data.toString())
  }
  fs.readFile('./SocketIo.html', function (err, data) {
    if (err) {
      console.log(err);
      callback('文件不存在')
    } else {
      callback(data)
    }
  })
})

app.get('/SocketIOClient.js',function(req,res){
  fs.readFile('./public/SocketIOClient.js',(err,data)=>{
    res.send(data)
  })
})
app.get('/socket.io.js',function(req,res){
  fs.readFile('./public/socket.io.js',(err,data)=>{
    res.send(data)
  })
})

// socket.io设置
// 在线用户
var onlineUsers = {}

var i = 0

io.on('connection', function (socket) {
  console.log('有人连上来了~');
  //监听新用户的加入
  socket.name = '用户' + ++i
  onlineUsers[socket.name] = socket

  // 监听用户退出
  socket.on('disconnect', function () {
    console.log('有人退出');
    delete onlineUsers[socket.name]
  })

  // 监听用户发布聊天内容
  socket.on('message', function (msg) {
    broadcast(msg, socket)
  })
})

function broadcast(msg, socket) {
  for (var key in onlineUsers) {
    onlineUsers[key].send(socket.name + ' : ' + msg)
  }
}

server.listen(9000, function () {
  console.log('Port:9000 | Running ...');
})

Guess you like

Origin blog.csdn.net/weixin_52203618/article/details/129639486