2012-04-24 2 views
2

저는 웹 개발과 웹 테크놀로지에 익숙하지 않습니다. 학습을 위해 나는 websocket과 멀티 플레이어 게임을 cretate하려고합니다. 게임은 "더 큰 단어 만들기"입니다.이 글에서는 WIN에서 그 단어가 큰 단어를 가진 사용자와 사용자에게 "임의"문자를 입력하는 코드를 작성합니다.socketIO로 개발중인 웹 게임

나는 코드를 가지고 있지만 socket.io API를 통해 기본으로 단어를 만들기 위해 편지를주고

코드 연결과 함께 seriuos 문제가 :

<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);}); 

정지 DIV에 사용자가 클릭 한 후을 그들은 $ 편지를 얻을 ... 그래서 PHP를 통해 기지에서 $를 얻을 수 있지만 socket.io을 통해 서버에서 클라이언트에게이 $를 보내는 방법은 매우 쉽다.

for 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를 구현하여 클라이언트에서 서버로 $를 가져 오는 방법 ... 서버에서 클라이언트로 $를 보내는 방법 ???

는 (미안 내 영어를 들면, 나는 웹 기술에 beginer에이야. 사소한 질문에 대한 죄송)

+0

도 여기에 작동 버전 : http://jsfiddle.net/ Hx28c/3/ –

+0

아무도 몰라? ... –

+1

기본적으로 말하길, 여기 내 모든 코드가 있는데, 뭐가 잘못 되었습니까? 일반적으로 관련 코드 조각만으로 매우 구체적인 질문을하게됩니다. 이것은 매우 모호한 질문이며이를 통해 살펴볼 소설이 있습니다. – dqhendricks

답변

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

+0

그래서이 코드로 코드를 변경하고 작업을해야합니다. –

+0

내 생각에 위의 방식으로 정렬해야합니다. :) –

+0

괜찮 으면 시도 할 것이지만 그렇게 생각하지는 않습니다 ...어디에서이 코드를 추가해야합니까? 도와주세요 ... 그리고 지루해해서 미안하지만이 tehnology에서 매우 흥미 롭습니다. –

관련 문제