开发者

Socket.io calling http://undefined/.... in the URL

开发者 https://www.devze.com 2023-03-18 02:58 出处:网络
I\'m starting with socket.io with a simple exemple : Client Side : $(document).ready(function () { var sock = new io.Socket();

I'm starting with socket.io with a simple exemple :

Client Side :

    $(document).ready(function () {      
    var sock = new io.Socket();      
    sock.on('message', function (data) {        
        var obj = JSON.parse(data);        
        if(obj.message) {          
            $('#message').text(obj.message);        
      开发者_StackOverflow  } else {          
            $('#timestamp').text(obj.timestamp);          
            $('#clients').text(obj.clients);        }      });      

    sock.connect('http://127.0.0.1:8333');      
    $("#poke").click(function() { 
        sock.send("Poke !"); 
    });     
});

Server Side:

var io = require('socket.io');var express = require('express');
var app = express.createServer();
app.configure(function(){  
    app.use(express.static(__dirname + '/public'));});
    app.get('/', function(req, res, next){  res.render('./public/index.html');});
app.listen(8333);

var socket = io.listen(app, {  
    flashPolicyServer: false,  
    transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling']});
var allClients = 0;
var clientId = 1;
socket.on('connection', function(client) {  var my_timer;  var my_client = { "id": clientId, "obj": client };
  clientId += 1;
  allClients += 1;
  my_timer = setInterval(function () {    
    my_client.obj.send(JSON.stringify({ "timestamp": (new Date()).getTime(), "clients": allClients }));  }, 1000);  
    client.on('message', function(data) {    my_client.obj.broadcast(JSON.stringify({ message: "poke send by client "+my_client.id }));    
    console.log(data);  
 });

client.on('disconnect', function() {    
    clearTimeout(my_timer);    
    allClients -= 1;    
    console.log('disconnect');  });});

My problem is that the client is trying to get :

http://undefined/socket.io/1/?t=1310142283769&jsonp=0

Wich is undefined. When I curl my app with http://localhost/socket.io/1/?t=1310142283769&jsonp=1 i get something.

Why socket is calling undefined whereas everything seems to be set correctly.

Thank you if you can help me !


It looks like you are incorrectly creating the socket in your client. You should have something more like:

var sock = io.connect('http://127.0.0.1:8333');

and remove the sock.connect line entirely.

You should look over the examples on the SocketIO website. http://socket.io/#how-to-use


I just encountered the same thing. For me, it was code written against Socket.IO v0.6 causing the issue—since I had last worked with Socket.IO it has updated to v0.7! There's a migration guide available here:

https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7+

0

精彩评论

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