简体   繁体   中英

socket.io-client: Can't call the “connect” function

I have the following code:

var io = require('socket.io-client');

function connect_to_room(callback){
    console.log(typeof io.connect);
    var socket = io.connect('http://website.com/socket/');
    socket.on('connect', function(){
        console.log("connected");
        socket.on('event', function(data){
            console.log("event happened");
            console.log(data);
        });
        socket.on('disconnect', function(){
            console.log("disconnected");
        });
    });
}

exports.connect = connect_to_room();

When I call connect_to_room() , it logs "function" in the console, and then throws me this error:

TypeError: Property 'connect' of object #<Object> is not a function
    at Request._callback (C:\Users\randomuser\Downloads\somecode\somecode\dev\init.js:151:35)
    at Request.self.callback (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:121:22)
    at Request.EventEmitter.emit (events.js:98:17)
    at Request.<anonymous> (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:978:14)
    at Request.EventEmitter.emit (events.js:117:20)
    at IncomingMessage.<anonymous> (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:92
9:12)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

What am I doing wrong here?

node --version returns v0.10.26

package.json has this for dependencies (which are all installed):

"dependencies" : {
    "jsonfile"          : "1.1.1",
    "log4js"            : "0.6.12",
    "mkdirp"            : "0.3.5",
    "npm"               : "1.4.4",
    "request"           : "2.34.0",
    "jsdom"             : "0.10.2",
    "socket.io-client"  : "0.9.16"
},

You have a typo

var sock

should be

var socket

Another problem:

exports.connect = connect_to_room();

Should be

exports.connect = connect_to_room;

Try this:

var socket = require('socket.io-client')('http://website.com/socket/');

function connect_to_room(callback){
    console.log(typeof io.connect);
    socket.on('connect', function(){
        console.log("connected");
        socket.on('event', function(data){
            console.log("event happened");
            console.log(data);
        });
        socket.on('disconnect', function(){
            console.log("disconnected");
        });
    });
}

exports.connect = connect_to_room(function(back){ });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM