gpt4 book ai didi

javascript - Node.js:TypeError:对象 socket.io 没有方法 'listen'

转载 作者:行者123 更新时间:2023-11-30 10:35:02 24 4
gpt4 key购买 nike

我正在使用 Express 3.0.6 使用 socket.io 0.9.13 制作一个小 Node 应用程序。我什至无法开始运行,因为它说 socket.io 没有方法 listen()。这是我的代码(编译的 coffeescript,所以有点难看):

(function() {
var app, express, io, port, usernames;

express = require('express');

app = express();

io = require('socket.io'.listen(3000));

port = 3000;

app.listen(port);

console.log("Listening on port " + port);

console.log('CNTRL-C to quit.');

app.engine('hamlc', require('haml-coffee'.__express));

app.get('/', function(request, response) {
return response.render('index.hamlc');
});

usernames = {};

io.sockets.on('connection', function(socket) {
socket.on('send-chat', function(msg) {
return io.sockets.emit('update-chat', socket.username, msg);
});
socket.on('add-user', function(username) {
socket.username = username;
usernames[username] = username;
socket.emit('update-chat', 'SERVER', "You have connected as " + username + ".");
socket.broadcast.emit('update-users', 'SERVER', "" + username + " has joined the chat.");
return io.sockets.emit('update-users', usernames);
});
return socket.on('disconnect', function() {
delete usernames[socket.username];
io.sockets.emit('update-users', usernames);
return socket.broadcast.emit('update-chat', 'SERVER', "" + socket.username + " has disconnected from chat");
});
});

}).call(this);

这引发了以下错误:

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object socket.io has no method 'listen'
at Object.<anonymous> (/Users/chris/src/web/kouv/app.js:8:28)
at Object.<anonymous> (/Users/chris/src/web/kouv/app.js:44:4)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)

非常感谢回答。 :-)

最佳答案

试试这个:

var express = require('express'),
http = require('http');

var app = express();
var server = http.createServer(app);

var io = require('socket.io').listen(server);
server.listen(3000);

Socket.io 本质上是在运行时劫持 http 对象;不过,express 3.xx 不再运行 http.server,因此有必要创建您自己的实例以供 socket.io 使用。

关于javascript - Node.js:TypeError:对象 socket.io 没有方法 'listen',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com