开发者

Creating a hello world application with socket.io

When I run on the client the Hello World is prin开发者_运维问答ted but what console log I have written that does not shown event on client and server both. Why?

Client code:

<script src="C:\cygwin\usr\local\lib\node\.npm\socket.io\0.6.10\package\support\socket.io-client\socket.io.js"></script> 
<script> 
 var socket = new io.Socket('http://localhost:8080/'); 
 socket.connect();
 socket.on('connect', function(){
    console.log("on connect");

 }) ;
 socket.on('message', function(){ 
    console.log("on message");

 }) ;
 socket.on('disconnect', function(){ 
    console.log("on disconn");
 }) ;
</script> 

Server code:

var http = require('http'),  
    io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io') 

server = http.createServer(function(req, res){ 
 // your normal server code 
 res.writeHead(200, {'Content-Type': 'text/html'}); 
 res.end('<h1>Hello world</h1>'); 
});
server.listen(8080);

// socket.io 
var socket = io.listen(server); 
socket.on('connection', function(client){ 
  // new client is here! 
  client.on('message', function(){ 
    console.log("on message");
  }) 
  client.on('disconnect', function(){
    console.log("on disconnect");
  }) 
}); 


Try

var socket = new io.Socket('localhost:8080'); 

instead of

var socket = new io.Socket('http://localhost:8080/');


It's probably because of browser same origin security restriction - socket.io client library doesn't come from the server you connect to.

I don't know about rather ancient 0.6.9, but newer versions of socket.io serve socket.io client automatically, so you should use /socket/socket.io.js instead of file:// URL you currently use. Check the documentation for exact URL.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜