首页 > 代码库 > node的express中使用socket.io

node的express中使用socket.io

服务器端server.js代码

 1 var express=require("express"); 2 var http=require("http"); 3 var sio=require("socket.io"); 4 var app=express(); 5 var server=http.createServer(app); 6 var fs=require("fs"); 7 app.get("/", function (req,res) { 8    res.sendfile(__dirname+"/index.html"); 9 });10 server.listen(1337);11 var socket=sio.listen(server);12 socket.on("connection", function (socket) {13     socket.emit("news",{hello:"你好"});14     socket.on("otherEvent", function (data) {15         console.log("服务器端接受到数据:%j",data);16     })17 });

 

客户端index.html代码

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title></title> 6     <script src="/socket.io/socket.io.js"></script> 7     <script> 8         var socket=io.connect(); 9         socket.on("news", function (data) {10             console.log(data.hello);11             socket.emit("otherEvent",{my:"data"});12         });13     </script>14 </head>15 <body>16 17 </body>18 </html>

 

node的express中使用socket.io