简体   繁体   English

无法使用socket.io在Node.js服务器和客户端之间传递我的数据

[英]Can't communicate my data between nodejs server and client with socket.io

i'm begining at socket.io and node js. 我从socket.io和node js开始。 I'm trying to make a multiplayer "rock paper scissors" game. 我正在尝试制作多人“剪刀石头布”游戏。 Here is my server.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); 

and here is my index.html with my javascript code 这是我的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>

On my client side (index.html) i create a player object with name and choice attributes (rock, paper or scissor). 在我的客户端(index.html)上,我创建了一个具有名称和选择属性(岩石,纸张或剪刀)的播放器对象。 when a player click on a button its change choice value and then its send a player object to the server. 当玩家单击按钮时,其更改选择值,然后将玩家对象发送到服务器。

On my server side, i get values from each clients, add it to my gameServer object and send it to all clients then client will apply game logic to determine who win or lose. 在服务器端,我从每个客户端获取值,将其添加到我的gameServer对象中,然后将其发送给所有客户端,然后客户端将应用游戏逻辑来确定谁输谁赢。

When i connect with a user i got a log message on my server but i got this message on my browser. 当我与用户连接时,我在服务器上收到一条日志消息,但在浏览器上却收到了此消息。 "Cannot POST /". “无法发布/”。 I don't know why i got this and on my server my gameServer attributes are empty and i don't understand why data i emit from client aren't saved in my server. 我不知道为什么得到这个,在我的服务器上我的gameServer属性为空,我也不明白为什么我从客户端发出的数据没有保存在我的服务器中。

Do you have any idea? 你有什么主意吗?

When i connect with a user i got a log message on my server but i got this message on my browser. 当我与用户连接时,我在服务器上收到一条日志消息,但在浏览器上却收到了此消息。 "Cannot POST /". “无法发布/”。 I don't know why i got this 我不知道为什么我得到这个

The error "Cannot POST /" comes from your submit buttons in your form. 错误"Cannot POST /"来自表单中的提交按钮。 When a submit button is pressed in a form, the default behavior is to POST the form to the action URL. 在表单中按下提交按钮时,默认行为是将表单发布到操作URL。 Since that is not what you want, you have several ways to fix that. 由于这不是您想要的,因此有几种方法可以解决此问题。

First, if you have no intention of ever posting the form, then you can just remove the <form> tags entirely and change the buttons to regular <button> elements. 首先,如果您无意过帐表单,则可以完全删除<form>标记并将按钮更改为常规的<button>元素。 Then, there will be no default post just because a button was pressed. 然后,将不会有仅因为按下按钮的默认帖子。

You could also leave the HTML like it is and just prevent the default post behavior. 您还可以保持HTML不变,仅阻止默认的发布行为。 You would have to prevent the default behavior in each of your three click handlers like this: 您必须避免在这三个点击处理程序中的每个操作中出现默认行为,如下所示:

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

i don't understand why data i emit from client aren't saved in my server. 我不明白为什么我从客户端发出的数据没有保存在服务器中。

I don't see that you are actually sending any data to your server. 我看不到您实际上在向服务器发送任何数据。 You are calling: 您正在致电:

p.sendDataToServer();

which will send p.choice to your server. 它将p.choice发送到您的服务器。 But, this function call happens before any value has been set into either choice or p.choice . 但是,此函数调用发生在将任何值设置为choicep.choice Those values are only set LATER when the user clicks a button. 这些值仅在用户单击按钮后才设置。 Meanwhile, you've already called p.sendDataToServer() before any of those buttons were ever clicked. 同时,在您单击任何这些按钮之前,您已经调用了p.sendDataToServer() .on() creates event handlers. .on()创建事件处理程序。 These event handlers will be called sometime in the future when the user clicks a button. 这些事件处理程序将在将来用户单击按钮时的某个时间调用。 Meanwhile, the rest of your code continues to run. 同时,其余代码将继续运行。

Similarly, your call to p.getDataFromServer() just installs event handlers to listen for future data that might be sent from the server. 同样,对p.getDataFromServer()调用仅安装事件处理程序,以侦听将来可能从服务器发送的数据。 It doesn't actually get any data at that point in time. 在那个时间点它实际上没有任何数据。

It looks like you need a bit of a primer on how an event-driven system works. 看起来您需要一些关于事件驱动系统如何工作的入门知识。 You set up event handlers and then, sometimes in the future, when one of those event handlers is called, you then carry out an action in the event handler callback. 您设置了事件处理程序,然后有时在将来调用其中一个事件处理程序时,随后在事件处理程序回调中执行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM