Home > Web Front-end > JS Tutorial > body text

How to use socket.io_node.js in node's express

WBOY
Release: 2016-05-16 16:26:59
Original
1686 people have browsed it

Server-side server.js code

Copy code The code 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("Server received data: %j",data);
})
});

Client index.html code

Copy code The code is as follows:







<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:

Copy code The code 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 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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!