我在实施danielnill示例
时遇到以下错误当我在此示例中添加连接操作和客户端代码时,我收到此错误。
错误:
/home/oneadmin/Desktop/test-projects/nodejs/basic-example/server.js:40
io.sockets.on('connection', function(socket){
^
TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (/home/oneadmin/Desktop/test-projects/nodejs/basic-example/server.js:40:11)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:349:32)
at Function.Module._load (module.js:305:12)
at Function.Module.runMain (module.js:490:10)
at startup (node.js:124:16)
at node.js:807:3
server.js
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
response.end();
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(8001);
io.listen(server);
io.sockets.on('connection', function(socket){
socket.emit('message', {'message': 'hello world'});
});
socket.html
<html>
<head>
<script src="/socket.io/socket.io.js"> </script>
</head>
<body>
<script>
var socket = io.connect();
socket.on('message', function(data){
console.log(data.message);
});
</script>
<div> This is our socket.html file</div>
</body>
</html>
请帮助我理解错误,我该如何解决?
答案 0 :(得分:3)
您需要捕获socket.io的.listen()
的结果来设置服务器端侦听器:
server.listen(8001);
var ios = io.listen(server);
ios.sockets.on('connection', function(socket){
socket.emit('message', {'message': 'hello world'});
});
sockets
对象不是socket.io
模块本身的成员,而是io.Manager()
的侦听实例的成员。
在您关联的帖子中,其中一个片段中存在拼写错误(在“添加Socket.io ”下):
// ...
var io.listen(server);
我认为那应该是:
var io = io.listen(server);