【问题标题】:Can't communicate my data between nodejs server and client with socket.io无法使用 socket.io 在 nodejs 服务器和客户端之间通信我的数据
【发布时间】:2017-02-23 00:10:02
【问题描述】:

我从 socket.io 和 node js 开始。 我正在尝试制作多人“石头剪刀布”游戏。 这是我的 server.js

var app = require('express')(),
server = require('http').createServer(app)
io = require('socket.io').listen(server),
fs = require('fs');

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

function GameServer(){
this.p1 = ""
this.p2 = "";
this.choice1 = "";
this.choice2 = "";
this.countPlayer = 0;
}

GameServer.prototype = {
addPlayer: function(player){
    if(this.countPlayer < 1)
        this.p1 = player.name;
    else
        this.p2 = player.name;
},
addChoice: function(player){
    if(this.p1 == player.name)
        this.choice1 = player.choice;
    else if(this.p2 == player.name)
        this.choice2 = player.choice;
},
getData: function(data){
    //var gameData = {};
    if(this.p1 =="")
        this.p1 = data.p1;
    else if(this.p1 !="" && this.p2=="")
        this.p2 = data.p2;        
    if(this.choice1 =="")
        this.choice1 = data.choice1;
    else if(this.choice1 !="" && this.choice2=="")
        this.choice2 = data.choice2;
}
}

var game = new GameServer();

/* Connection events */
io.on('connection', function(client) {
client.on('ClientInfoGame', function(player){
    console.log('User '+player.name+' connected');
    console.log('he chose '+player.choice);
    game.getData(player);
});
console.log("on passe au emit")
client.emit('ServerInfoGame', {p1:game.p1,p2:game.p2,choice1:game.choice1,choice2:game.choice})
});

server.listen(8888); 

这是我的 index.html 和我的 javascript 代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Super Chat temps réel !</title>
        <style>
            #zone_chat strong {
                color: white;
            background-color: black;
            padding: 2px;
        }
    </style>
</head> 
<body>
    <h1>JANKEN GAME</h1>
    <form action="/" method="post">
        <input type="submit" id="r" value="Rock" />
        <input type="submit" id="p" value="Paper" />
        <input type="submit" id="s" value="Sissor" />
    </form>
    <h2 class="result"> Make a choice</h2> 
    <section id="zone_chat">
    </section>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
    function player(nom,choix,socket){
        this.name=nom;
        this.choice = choix;
        this.opponentChoice=""
        this.socket=socket
    }
    player.prototype.sendDataToServer = function() {
        //we send data from client to server
        //var data = this;
        this.socket.emit("ClientInfoGame",{name:this.name,choice:this.choice});
    };
    player.prototype.getDataFromServer = function() {
        //we get data from server 
        this.socket.on("ServerInfoGame",function(dataFromServer){
            var data = dataFromServer;
            if(data.p1 == this.name)
                this.opponentChoice = data.choice2;
            else if (data.p2 == this.name)
                this.opponentChoice = data.choice1;
        })
    };
    player.prototype.winnerIs = function() {
        console.log("opponnent choice ..."+ this.opponentChoice)

        if(this.choice == "Rock" && this.opponentChoice == "Rock" || this.choice == "Paper" && this.opponentChoice == "Paper" || this.choice == "Sissor" && this.opponentChoice == "Sissor" )
            return "Draaaaww , try again";   
        else if(this.choice == "Rock" && this.opponentChoice == "Sissor" || this.choice == "Paper" && this.opponentChoice == "Rock" || this.choice == "Sissor" && this.opponentChoice == "Paper" )
            return " YOU WIIIIIINNN ";  
        else if(this.opponentChoice == "Rock" && this.choice == "Sissor" || this.opponentChoice == "Paper" && this.choice == "Rock" || this.opponentChoice == "Sissor" && this.choice == "Paper" )
            return " YOU LOOOOOOSE ";
    };
    function end(p){
        $('h1.result').empty(); 
        $('h1.result').text(p.winnerIs()).html();
    }

        var choice = "";
        $('#r').on('click', function(){choice = "Rock"; p.choice = choice;})
        $('#p').on('click', function(){choice = "Paper"; p.choice = choice;})
        $('#s').on('click', function(){choice = "Sissor"; p.choice = choice;})
        var pseudo = prompt('What's your name?');
        // Connexion à socket.io
        var socket = io.connect('http://localhost:8888');
        var p = new player(pseudo,choice,socket);
        //document.title = pseudo + ' - ' + document.title;
//            socket.emit('choice', choice)
        //socket.emit("infoPlayer",p)
        p.sendDataToServer();
        p.getDataFromServer();            
        end(p);
    </script>
</body>

在我的客户端(index.html)上,我创建了一个具有名称和选择属性(石头、纸或剪刀)的玩家对象。 当玩家点击一个按钮时,它会更改选择值,然后将玩家对象发送到服务器。

在我的服务器端,我从每个客户端获取值,将其添加到我的 gameServer 对象并将其发送给所有客户端,然后客户端将应用游戏逻辑来确定谁赢或输。

当我与用户连接时,我在服务器上收到了一条日志消息,但我在浏览器上收到了这条消息。 “无法发布 /”。 我不知道为什么我得到这个,在我的服务器上我的 gameServer 属性是空的,我不明白为什么我从客户端发出的数据没有保存在我的服务器中。

你有什么想法吗?

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    当我与用户连接时,我在服务器上收到了一条日志消息,但我在浏览器上收到了这条消息。 “无法发布 /”。我不知道为什么我得到这个

    错误"Cannot POST /" 来自表单中的提交按钮。在表单中按下提交按钮时,默认行为是将表单发布到操作 URL。由于这不是您想要的,您有多种方法可以解决此问题。

    首先,如果您不打算发布表单,那么您可以完全删除&lt;form&gt; 标签并将按钮更改为常规&lt;button&gt; 元素。然后,不会因为按下按钮而默认发布。

    您也可以保留 HTML 原样并阻止默认的发布行为。您必须阻止三个点击处理程序中的每一个中的默认行为,如下所示:

    $('#r').on('click', function(e){
        // prevent default post of form
        e.preventDefault();
        choice = "Rock"; 
        p.choice = choice;
    });
    

    我不明白为什么我从客户端发出的数据没有保存在我的服务器中。

    我没有看到您实际上正在向您的服务器发送任何数据。你在打电话:

    p.sendDataToServer();
    

    这会将p.choice 发送到您的服务器。但是,此函数调用发生在将任何值设置为 choice 或 p.choice 之前。这些值仅在用户单击按钮时设置。同时,在单击任何这些按钮之前,您已经调用了p.sendDataToServer()。 .on() 创建事件处理程序。这些事件处理程序将在未来某个时间当用户单击按钮时被调用。同时,您的其余代码继续运行。

    同样,您对p.getDataFromServer() 的调用只是安装事件处理程序以侦听可能从服务器发送的未来数据。它实际上并没有在那个时间点获得任何数据。

    您似乎需要了解一下事件驱动系统的工作原理。您设置事件处理程序,然后有时在将来调用其中一个事件处理程序时,您在事件处理程序回调中执行操作。

    【讨论】:

    • 感谢您的回答。你是对的,我什至不习惯处理。我会对此做更多的研究。 :)
    猜你喜欢
    • 2017-01-29
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多