Socket.io 404错误
我遵循了Jeffrey方式的教程。 教程:
这是我的index.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function(request, response){
response.sendFile(__dirname+'/index.html');
});
io.on('connection', function(socket){
console.log('A connection is made');
});
有人说它的版本和年份。我认为上面的代码适用于2014年。
这是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Chat Lesson</title>
</head>
<body>
<h1>Hello world!</h1>
<script src=".io/2.0.4/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
</script>
</body>
</html>
我做了很多研究。有人说序列很重要,但我找到了很多序列。
我的错误:
GET :8888/socket.io/?EIO=3&transport=polling&t=1515636281477-74 404 (Not Found)
我的问题: 为什么没有找到404?我在每一步都遵循了Jeffrey方式的教程,教程只有5-8分钟。
- Mamp Pro 4
- NPM 3.10.10
我尝试使用server.listen(8888);
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::8888
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at Object.<anonymous> (/Users/kendantinio/Documents/Freelancer/blvnp/chat-lesson/index.js:5:8)
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)
回答如下:
尝试执行此代码。
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some other username.');
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
如果有效,请告诉我。