使用socketIO开发的网页游戏

时间:2012-04-24 20:25:08

标签: php javascript html socket.io

我是网络开发和网络技术的新手。为了学习我正试图用websocket创建一个多人游戏。游戏是“让更大的词汇”在这里我写了一个代码,从基地到用户以及那个字母更大的用户获得“随机”字母。

我有一个代码,但是通过socket.io API

连接base会遇到严重问题

用于创建单词的代码:

<div id="s">STOP</div>

<div id="L1"></div>
<div id="L2"></div>
<div id="L3"></div>
<div id="L4"></div>
<div id="L5"></div>

$a="AGHBV";

v=setInterval(function(){for(i=0;i<6;i++){$("#L"+i).html(String.fromCharCode(Math.floor(Math.random()*26+65)))};},500);$("#s").click(function(){clearInterval(v);setTimeout(function(){for(j=0;j<$a.length;j++){$("#L"+(j+1)).html($a[j]);}},250);});

当用户点击STOP div然后他们得到$ a字母......所以当你通过php从基础获得$时如此容易但是如何通过socket.io从服务器向客户端发送$ $

对于socket.io我有一些代码,但我不知道如何正确工作。

这是套接字客户端文件:

<!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://cdn.socket.io/stable/socket.io.js"></script>
    <script>

        // Create SocketIO instance
        var socket = new io.Socket('localhost',{
            port: 8080
        });
        socket.connect(); 

        // Add a connect listener
        socket.on('connect',function() {
            log('<span style="color:green;">Client has connected to the server!</span>');
        });
        // Add a connect listener
        socket.on('message',function(data) {
            log('Received a message from the server:  ' + data);
        });
        // Add a disconnect listener
        socket.on('disconnect',function() {
            log('<span style="color:red;">The client has disconnected!</span>');
        });

        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.send(message);
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }

        /*
        // Create a socket instance
        socket = new WebSocket('ws://localhost:8080');

        // Open the socket
        socket.onopen = function(event) {
            console.log('Socket opened on client side',event);

            // Listen for messages
            socket.onmessage = function(event) {
                console.log('Client received a message',event);
            };

            // Listen for socket closes
            socket.onclose = function(event) {
                console.log('Client notified socket has closed',event);
            };

        };
        */

    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>

</body>
</html>

这里是套接字服务器文件:

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

    // Success!  Now listen to messages to be received
    client.on('message',function(event){ 
        console.log('Received message from client!',event);
    });
    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});

我需要做些什么才能得到我需要的东西。如何在我的脚本中实现socketIO以从服务器到客户端获取$ ...如何做该服务器从客户端发送一个$ $ ???

(对不起我的英语,我是网络技术的先生。很抱歉一个小问题)

1 个答案:

答案 0 :(得分:2)

这是一个很好的例子,说明如何从服务器向客户端和客户端发送消息到服务器。本文适合您,因为您有一个拥有多个客户端的游戏。所以我认为最好的选择是在客户端之间广播消息。

在服务器..

io.sockets.on('connection', function (socket) {
    console.log('Socket Created...');

      socket.on('sendMessage', function (data) {
        socket.broadcast.emit('messageRecieve', data);
    });
});

在客户端,

   socket.on('messageRecieve', function (data) {//receive broadcasted message from server
        AppendMessage(data.msg);
    });

     function SendMessage() {// sends the message from client to the server may be on click
        var message = document.getElementById('text').value;
        socket.emit('sendMessage', { msg: message });
        AppendMessage(message);
    }

以下是http://codetuner.blogspot.com/2012/04/real-time-web-sample-using-socketio-and.html

的详细信息