码迷,mamicode.com
首页 > Web开发 > 详细

node express4.0+socket.io整合 访问不到 socket.io.js问题

时间:2015-07-02 15:58:07      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

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>




node express4.0+socket.io整合 访问不到 socket.io.js问题

标签:

原文地址:http://my.oschina.net/diqye/blog/473497

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!