0

我目前正在使用 nodeJS 机器人应用程序,我正在尝试使用 sockets.io 在浏览器中显示一些消息和数据。

我有以下nodeJS代码:

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('A user connected');
      socket.on('clientEvent', function(data){
            function take_tool() {
                while(!take_tool_flag) {
                    if(fs.existsSync('D:/flag.txt')) {
                        fs.writeFileSync('D:/input_robot.txt', '-1');
                        socket.emit('testerEvent', 'Robot is taking the writing tool!');
                        console.log('Robot is taking the writing tool!');
                        fs.unlinkSync('D:/flag.txt');
                        take_tool_flag = true;
                    }
                }
            }
            function draw_table() {
                while(!draw_table_flag && take_tool_flag) {
                    if(fs.existsSync('D:/flag.txt')) {
                        fs.writeFileSync('D:/input_robot.txt', '-3');   
                        socket.emit('testerEvent', 'Robot is drawing the table game!');   
                        console.log('Robot is drawing the table game!');
                        fs.unlinkSync('D:/flag.txt');
                        draw_table_flag = true;
                    }
                }
            }
            function game() {

                socket.emit('testerEvent', 'A new game has started!');
                console.log("A new game has started!");

                fs.writeFileSync('D:/input_robot.txt', '-99');

                if(!take_tool_flag) { take_tool(); }

                if(!draw_table_flag) { draw_table(); }
            }

            game();
      });
      socket.on('disconnect', function () {
        console.log('A user disconnected');
      });
});

http.listen(3000, function(){
  console.log('listening on localhost:3000');
});

然后在 HTML 中:

<!DOCTYPE html>
<html>
    <head><title>Hello world</title></head>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      socket.on('testerEvent', function(data){document.write(data)});

      function start() {
        socket.emit('clientEvent', 'Sent an event from the client!');
      }
    </script>
    <body>Hello world
        <button onclick="start()">Start</button>
    </body>
</html>

当我按下 html 中的开始按钮时,game() 中的前 3 条指令;函数执行:

socket.emit('testerEvent', 'A new game has started!');
console.log("A new game has started!");

fs.writeFileSync('D:/input_robot.txt', '-99');

我从 socket.emit 在浏览器中获取消息;

然后进入take_tool(); 等待“D:/flag.txt”创建的函数。当我创建这个文件时执行 take_tool(); 继续,但我没有在浏览器中收到来自 socket.emit 的消息。draw_table(); 同样的事情 功能。我在游戏结束时收到这些消息();函数执行。我需要在浏览器中实时显示这些消息,而不是在函数执行结束时。似乎是什么问题?谢谢!

4

0 回答 0