我正在尝试使用我的角度Js项目实现Socket IO。我是新手,请帮助。
这是我的 server.js 文件
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on('connection'), function(socket){
console.log('new connection made');
}
server.listen(port, function(){
console.log('Listening to port '+ port);
})
我已经从socket.io-client复制了socket.io.js文件并将其放在我的 lib 文件夹中。所以我的 index.html 有
<script src="lib/js/socket.io.js"></script>
//all other includes required
<body>
//code here
</body>
继承人是我在执行 nodemon server.js时看到的错误
[nodemon] starting `node server.js`
events.js:216
throw new TypeError('"listener" argument must be a function');
^
TypeError: "listener" argument must be a function
at _addListener (events.js:216:11)
at Namespace.addListener (events.js:275:10)
at Server.(anonymous function) [as on]
(D:\SocketIOExperiment\ProjExperiment\node_modules\socket.io\lib\index
.js:456:29)
at Object.<anonymous>
(D:\SocketIOProject\SmartAdminExperiment\server.js:11:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
[nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:2)
您的代码上的小错误。请尝试:
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on(('connection'), function(socket){
console.log('new connection made');
})
server.listen(port, function(){
console.log('Listening to port '+ port);
})
请记住,io.on(event,cb)是一个函数调用,它将cb函数注册到事件中。