Server-side server.js code
The code copy is as follows:
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 accepts data:%j",data);
})
});
Client index.html code
The code copy is as follows:
<!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>
Suddenly I thought of a question: Can I write the listening code of news to the same end as emit?
so:
The code copy is as follows:
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("Start listening 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 the 15~17 lines of code: it was newly added by us.
It turns out that it is not possible, and there will be no printing. However, there will be no errors.
The execution of emit is called "send event". If there are parameters, the name is called "carrying parameters".
postscript:
I have also found a lot of session calling methods in the Express framework online, but I found that not many of them can be used. This article is a specific method of using session in Express and socket.IO based on the production process of my own project.