Server-side Server.js code
Copy Code code 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-side acceptance of data:%j";
})
});
Client index.html Code
Copy Code code as follows:
<! DOCTYPE html>
<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>
<body>
</body>
A question suddenly came to mind. Can I write news's listening code to the same end as emit?
Such
Copy Code code 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 15~17 Line code: We added the new one.
It turns out not to be possible, there won't be any printing. But it's not going to be an error.
Emit's execution, the name of the United States: Send events. If there are parameters, the name Yue: Carry parameters.
Postscript:
On the internet also found a lot about the express framework of the session call method, but found that the real can not use a lot, this article is based on their own project production process, organized express and Socket.io in the use of the specific method of session.