How to Use socket. io and nodesocket. io in node express
Server. js Code
Copy codeThe 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 ("data received by the server: % j", data );
})
});
Client index.html code
Copy codeThe Code 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>
I suddenly thought of a problem. Could I write the news listening code to the same end as the emit.
In this way:
Copy codeThe 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 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 ~ 17 lines of code: We added it.
It turns out that no printing is allowed, but no error is reported.
Emit execution. Its name is "send event". If there is a parameter, its name is "carry parameter.
Postscript:
I also found a lot of session calling methods in the Express framework on the Internet, but I found that not many of them are actually usable. This article is based on the production process of my own project, organized by Express and socket. IO.