我有一对server.js和client.js脚本文件。
这是server.js文件......
var express = require('express');
var appMain = express(); var appReset = express();
var serverMain = require('http').Server(appMain);
var serverReset = require('http').Server(appReset);
var fs = require('fs');
appMain.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
appMain.use('/client', express.static(__dirname + '/client'));
appReset.get('/', function(req, res) {
res.sendFile(__dirname + '/client/reset.html');
});
appReset.use('/client', express.static(__dirname + '/client'));
serverMain.listen(3000); console.log('Start mainServer');
serverReset.listen(2000); console.log('Start resetServer');
var gameScores;
fs.readFile('client/data/scores.txt', 'utf8', function(error, data) {
if (error) {
console.log('Read Error!');
gameScores = null;
}
else {
console.log('Read Success!');
gameScores = data;
}
});
var ioMain = require('socket.io') (serverMain,{});
ioMain.sockets.on('connection', function(socket) {
console.log('mainSocket Connected');
socket.emit('gameScores', gameScores);
socket.on('gameScores', function(data) {
gameScores = data;
fs.writeFile('client/data/scores.txt', JSON.stringify(data), function(error) {
if (error)
console.log('Write Error!');
else
console.log('Write Success!');
});
socket.emit('gameScores', gameScores);
});
});
var ioReset = require('socket.io') (serverReset,{});
ioReset.sockets.on('connection', function(socket) {
console.log('resetSocket Connected');
socket.on('resetScores', function(data) {
fs.unlink('client/data/scores.txt', function(error) {
if (error) {
console.log('Delete Error!');
socket.emit('clearScores', false);
}
else {
console.log('Delete Success!');
gameScores = null;
socket.emit('defaultScores', gameScores);
socket.emit('clearScores', true);
}
});
});
});
这是client.js文件......
socket.on('gameScores', function(data) {
if (data !== null) {
if (JSON.parse(localStorage.reload))
localStorage.reload = false;
else
localStorage.gameScores = JSON.stringify(data);
localStorage.emptyScores = false;
}
else {
localStorage.emptyScores = true;
localStorage.reload = false;
}
});
socket.on('defaultScores', function(data) {
if (data == null) {
console.log('Received Default from Server');
localStorage.emptyScores = true;
Game.main.gameScores('load');
}
});
这两个文件的所有代码都正常工作,但在server.js文件中,您会看到注释“删除成功!”接下来是三行代码。在这三行中,不起作用的具体行如下:
socket.emit('defaultScores', gameScores);
上面的代码行应该将数据包发送到标签“defaultScores”的client.js文件中的相应套接字接收者,但客户端从不接收它。我知道客户端没有收到它,因为评论“从服务器收到默认值”不会打印到客户端控制台。一旦有问题的套接字接收器能够成功工作,从而打印出有问题的评论,其余部分应该可以正常工作。
因此,我特别要求协助获取评论“从服务器接收默认值”以成功打印到客户端控制台。