2012-02-29 15 views
1

以下是我在嘗試測試基本Socket.io和Express設置時出現的錯誤(根據socket.io網站上的示例):Socket.io和Express出現錯誤「沒有方法套接字」

/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:659 

     var socket = this.namespaces[i].socket(data.id, true); 



^ 

TypeError: Object function extend(another) { 
    var properties = Object.keys(another); 
    var object = this; 
    properties.forEach(function (property) { 
    object[property] = another[property]; 
    }); 
    return object; 
} has no method 'socket' 
    at Manager.handleClient (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:659:41) 
    at Manager.handleUpgrade (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:588:8) 
    at HTTPServer.<anonymous> (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:119:10) 
    at HTTPServer.emit (events.js:88:20) 
    at Socket.<anonymous> (http.js:1390:14) 
    at TCP.onread (net.js:334:27) 

感謝所有幫助我可以,請:)

+0

應該清楚,你從this.namespaces得到的任何項目都不包含一個名爲socket的方法。粘貼更多的代碼,如果你想幫助追查真正的問題。 – 2012-02-29 20:05:40

+0

通常,套接字不是一種方法,它是一個對象,您需要在給定套接字上調用'.emit()'或'.write()'。 – 2012-02-29 20:52:49

+0

我正在使用Express的socket.io網站的確切示例:[link](http://socket.io/#how-to-use)<~~ Socket.io「如何使用」 – scottcorgan 2012-02-29 21:46:17

回答

0

this.namespaces[i].socket(data.id, true);不存在。做類似console.log(typeof this.namespaces[i].socket(data.id, true));你可能會得到一個undefined

我敢打賭你的命名空間數組的一個元素缺失。

+0

你是什麼意思的命名空間數組? – scottcorgan 2012-03-01 17:07:04

1

此問題的事實,你或者你使用一個庫中添加功能Object.prototype中莖。

因此,這個代碼:

Object.prototype.foo = function() {}; 
Object.prototype.bar = function() {}; 

var myObj = { x: 1 }; 

for (var i in myObj) { 
    console.log(i) 
} 

會打印:X,FOO,酒吧(按順序不一定),而不是僅僅X如您所願。

你的情況,這種情況發生在manager.js:

// initialize the socket for all namespaces 
for (var i in this.namespaces) { 
    var socket = this.namespaces[i].socket(data.id, true); 

    // echo back connect packet and fire connection event 
    if (i === '') { 
     this.namespaces[i].handlePacket(data.id, { type: 'connect' }); 
    } 
} 

此代碼不會想到會遇到聲明:延長鍵,你可以從錯誤的堆棧跟蹤看到:

TypeError: Object function extend(another) { 
    var properties = Object.keys(another); 
    var object = this; 
    properties.forEach(function (property) { 
    object[property] = another[property]; 
    }); 
    return object; 
} has no method 'socket' 

程序實際上是試圖調用插座()延伸功能。

有關將函數添加到Object.prototypeBob's rant here

至於解決,您可以添加一個條件語句中manager.js像這樣:

// initialize the socket for all namespaces 
for (var i in this.namespaces) { 
    if ('extend' == i) continue; // ADDED 
    var socket = this.namespaces[i].socket(data.id, true); 

    // echo back connect packet and fire connection event 
    if (i === '') { 
     this.namespaces[i].handlePacket(data.id, { type: 'connect' }); 
    } 
} 

,或者你可以刪除Object.prototype.extend =功能(...){ }聲明,這是我個人的偏好。