通过socket.io解析表单数据并检索数据

时间:2015-01-02 07:23:38

标签: jquery node.js express socket.io

我正在尝试通过主机解析表单数据,该主机将在第二屏风格的Web应用程序中发送给客户端,但是我很难获取表单数据,特别是来自主机和客户端的nameTheBet。 / p>

我错过了什么?代码如下:

HTML Block

<script id="create-game-template" type="text/template">
    <div class="createGameWrapper">
        <div id="betSummary">
            <div class="info">
                <span class="nameTheBet"></span>
            </div>
        </div>

        <div class="info">Open this site on your mobile device:</div>

        <div id="gameURL" class="infoBig">Error!</div>
            <div class="info">Then click <strong>JOIN</strong> and <br/> enter the following Game ID:</div>
            <div id="spanNewGameCode" class="gameId">Error!</div>
        <div id="playersWaiting"></div>
    </div>
</script>

存储数据

onCreateClick: function () {

IO.socket.emit('hostCreateNewGame');

var data = {
    gameId : +($('#inputGameId').val()),
    placeBet : +($('#inputPlaceBet').val()),
    nameTheBet : $('#inputNameTheBet').val(),
    playerName : $('#inputPlayerName').val() || 'anon'
};
$('#betSummary')
    .append('<p/>')
    .text(data.nameTheBet);

IO.socket.emit('nameTheBet', data);

// Set the appropriate properties for the current player.
App.myRole = 'Host';
App.Host.myBet = data.nameTheBet;
},

检索

function nameTheBet(data) {

io.sockets.in(data.gameId).emit('nameTheBet', data);
}

2 个答案:

答案 0 :(得分:1)

我从头开始重写了我的函数,并在从客户端解析到服务器然后向客户端发回的每一步调试。从服务器发回服务器是问题所在。

存储数据

onCreateClick: function () {

    var data = {
        nameTheBet : $('#inputNameTheBet').val() || 'anon',
        playerName : $('#inputPlayerName').val() || 'anon'
    };

    IO.socket.emit('hostCreateNewGame', data);

    App.myRole = 'Player';
    App.Player.myBet = data.nameTheBet;
},

服务器端

function hostCreateNewGame(data) {
    // Create a unique Socket.IO Room
    var thisGameId = ( Math.random() * 100000 ) | 0;
    var thisBet = data.nameTheBet

    this.emit('newGameCreated', {gameId: thisGameId, mySocketId: this.id, nameTheBet: thisBet});

    this.join(thisGameId.toString());
}

这样做......

onNewGameCreated : function(data) {
    App.Host.gameInit(data);
    App[App.myRole].setTheBet(data);
    console.log(data.nameTheBet);
},

附加HTML块

setTheBet : function(data) {
    $('#betSummary')
        .append('<p/>')
        .text(data.nameTheBet);
},

答案 1 :(得分:0)

我相信当你发出数据时,它需要包含在一个on连接函数中,它看起来像:

IO.on('connection', function(socket){
  //your code here
  socket.emit('nameTheBet', data);
});

*编辑在这两个地方你都在散发,但我看不到你在哪里听socket.on('nameTheBet')