server.js 代码
var express=require("express"), pipe=require("./pipe.js"), app=express(), http=require(‘http‘).createServer(app) sio=require(‘socket.io‘).listen(http); // do....... sio.on(‘connection‘,function(socket){ console.log(‘connection‘); socket.on(‘msg‘,function(a){ console.log(a); sio.emit(‘msg‘,‘你妹妹‘); }); }); app.listen(7777,function(){ console.log("app started port is 7777"); });
执行 node server.js 运行后
在浏览器上访问 /socket.io/socket.io.js 为404
折腾了一个小时 终于解决了
将app.listen改成http.listen就好了
var express=require("express"), pipe=require("./pipe.js"), app=express(), http=require(‘http‘).createServer(app) sio=require(‘socket.io‘).listen(http); //js合并 pipe(app); //购物车 require("./cart.js")(app); app.engine("html",require("./lib/tpl-node.js")); //require(‘./test/websocket.js‘)(app); app.gome={ static:"E:\\workspaces\\dev\\Storefront\\storedocroot.war", jsserver:"http://localhost:7777", }; app.use(express.static(app.gome.static)); app.use(express.static(‘./test‘)); app.get("/",function(req,res){ res.send("index").end(); }); sio.on(‘connection‘,function(socket){ console.log(‘connection‘); socket.on(‘msg‘,function(a){ console.log(a); sio.emit(‘msg‘,‘你妹妹‘); }); }); http.listen(7777,function(){ console.log("app started port is 7777"); });
下面是一个完整的 server 和client js
server.js
var express=require("express"), pipe=require("./pipe.js"), app=express(), http=require(‘http‘).createServer(app) sio=require(‘socket.io‘).listen(http); //js合并 pipe(app); //购物车 require("./cart.js")(app); app.engine("html",require("./lib/tpl-node.js")); //require(‘./test/websocket.js‘)(app); app.gome={ static:"E:\\workspaces\\dev\\Storefront\\storedocroot.war", jsserver:"http://localhost:7777", }; app.use(express.static(app.gome.static)); app.use(express.static(‘./test‘)); app.get("/",function(req,res){ res.send("index").end(); }); sio.of(‘/test‘).on(‘connection‘,function(socket){ console.log(‘connection‘); socket.on(‘msg‘,function(a){ console.log(a); socket.emit(‘msg‘,‘你妹妹‘); }); }); http.listen(7777,function(){ console.log("app started port is 7777"); });
client.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script src="/socket.io/socket.io.js"></script> <script> socket = io.connect(‘ws://localhost:7777/test‘); socket.emit(‘msg‘,{hello:‘nimie‘}); socket.on(‘msg‘,function(a){ alert(a); }); </script> </body> </html>
时间: 2024-10-09 22:43:31