How do I use socket.io in express of node

  • 2020-05-05 10:54:55
  • OfStack

Server-side server.js code


 var express=require("express");
 var http=require("http");
 var sio=require("socket.io");
 var app=express();
 var server=http.createServer(app);
 var fs=require("fs");
 app.get("/", function (req,res) {
    res.sendfile(__dirname+"/index.html");
 });
 server.listen(1337);
 var socket=sio.listen(server);
 socket.on("connection", function (socket) {
     socket.emit("news",{hello:" hello "});
     socket.on("otherEvent", function (data) {
         console.log(" The server side receives the data :%j",data);
     })
 });

Client index.html code


 <!DOCTYPE html>
 <html>
 <head lang="en">
     <meta charset="UTF-8">
     <title></title>
     <script src="/socket.io/socket.io.js"></script>
     <script>
         var socket=io.connect();
         socket.on("news", function (data) {
             console.log(data.hello);
             socket.emit("otherEvent",{my:"data"});
         });
     </script>
 </head>
 <body>
 </body>
 </html>

A question occurred to me. Could I write news's listening code to the same end as emit?

Like this:


 var express=require("express");
 var http=require("http");
 var sio=require("socket.io");
 var app=express();
 var server=http.createServer(app);
 app.get("/", function (req,res) {
     res.sendfile(__dirname+"/index.html");
 });
 server.listen(1337,"127.0.0.1", function () {
     console.log(" To start listening to 1337");
 });
 var socket=sio.listen(server);
 socket.on("connection", function (socket) {
     socket.on("news", function (data) {
     console.log(data.hello);
     });
     socket.emit("news",{hello:" hello "});
 });

Note 15~17 lines of code: this is our new.

It turns out that it can't. There won't be any printing. But it won't be wrong either.

The execution of emit is called: send event. If there are parameters, it is called: carry parameter.

Postscript:

I also found a lot of session call methods in Express framework on the Internet, but I found that not many of them can be really used. This paper is based on the production process of my own project, sorting out the specific methods of using session in Express and socket.IO.


Related articles: