开发者

Simple nodeJS example not working with socket.io

开发者 https://www.devze.com 2023-03-02 08:53 出处:网络
Have been struggling all day trying to make this simple example work using socket.io. I\'ve tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.

Have been struggling all day trying to make this simple example work using socket.io. I've tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.

When running the script, it shows this...

2 May 20:57:47 - socket.io ready - accepting connections

But visiting the index.html page doesnt show a client has even connected.

index.html

<html>
<head>
<script type="text/javascript" src="socket.io.js"></script> 
<script type="text/javascript"> 
    var socket = new io.Socket('localhost',{'port':8090});

    socket.connect();

    socket.on('connect', function(){
        console.log('connected');
        socket.send('hi!'); 
    });

    socket.on('message', function(data){ 
        console.log('message recived: ' + data);
    });

    socket.on('disconnect', function(){
        console.log('disconected');
    });
</script> 
</head>
<body></body>
</html>

server.js

var http = require('http'), io = require('socket.io'),

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'tex开发者_StackOverflow社区t/html'}); 
    res.end('<h1>Hello world</h1>'); 
});
server.listen(8090);

var socket = io.listen(server); 
socket.on('connection', function(client){ 
    console.log('client connected');

    client.on('message', function(){ 
        console.log('message arrive');
        client.send('some message');
    });

    client.on('disconnect', function(){
        console.log('connection closed');
    });
});

Any ideas on what I could be doing wrong? No console messages whatsoever are being displayed. Notably, when i use Firebug to look at the index.html page, no scripts are being embedded, which is odd..Not sure what could be causing that.


You're not loading the socket.io library properly in your index.html file. Try this:

<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script> 


You're not serving up socket.io.js (or the flash file).

I'd recomend using the CDN:

<script src="http://cdn.socket.io/stable/socket.io.js"></script>

or alternatively use express to serve the socket.io.js file.

edit:

err actually looking closer you're also not serving up index.html again express could work but for the simple example:

var fs = require('fs');
var index = fs.readFileSync('index.html');
//note the readFileSync is done only in the first tic
.
.
.
res.writeHead(200, {'Content-Type': 'text/html'}); 
res.end(index); 


Use this on the client side as the path !

<script type="text/javascript" src="/socket.io/socket.io.js"></script> 


yes, and comment the following line:

// server.listen(8090);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号