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("Server received data: %j",data);
})
});
Client index.html code
<script><br>
var socket=io.connect();<br>
socket.on("news", function (data) {<br>
console.log(data.hello);<br>
socket.emit("otherEvent",{my:"data"});<br>
});<br>
</script>
A question suddenly occurred to me. Can I write the monitoring code for news to the same end as emit?
This way:
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 monitoring 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: they are newly added by us.
Facts prove that it is not possible, there will be no printing. But it will not report an error either.
The execution of emit is euphemistically called: sending an event. If there are parameters, it is euphemistically called: carrying parameters.
Postscript:
I also found a lot of information about the session calling methods in the Express framework on the Internet, but I found that not many of them are actually useful. This article is based on the production process of my own project, and compiled the specific methods of using sessions in Express and socket.IO.