正在学socket io,跟着官网的例子在做,代码如下所示: var app = require(‘express’).createServer(); var io = require(‘socket.io’)(app);
app.listen(80);
app.get(’/’, function (req, res){ res.end(“hello world”); });
io.on(‘connection’, function (socket) { socket.emit(‘news’, { hello: ‘world’ }); socket.on(‘my other event’, function (data) { console.log(data); }); }); 运行的时候报错了,错误信息如下所示: TypeError: undefined is not a function at Object.<anonymous> (/home/ubuntu/tmp/nodeproject/socketIO_express.js:1:92) at Module._compile (module.js:460:26) at Object.Module._extensions…js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3 node新手,不知道哪里有问题
不清楚这个写法是express的哪个版本的。你可以我下面这种写法。
var app = require('express')();
var http = require('http');
var port = 8080;
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(port, function() {
console.log('[%s] Listening on http://localhost:%d', 'development', port);
});
app.get('/', function (req, res){
res.end('hello world');
});
io.on('connection’', function (socket) {
socket.emit('news’', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
改成如下便可
var app = express(); var server=app.listen(8080); //socket io listen var io = require(‘socket.io’).listen(server);
@okoala 你的方法我试了一下,没有问题。我用的express版本是4.12.3。谢谢
@zhang852774731 刚改了下,漏了一个var~