试图弄清楚如何制作一个简单的网络游戏需要一些帮助

时间:2011-12-07 16:00:42

标签: java tcp

我正在写一个简单的读卡游戏。 这个想法是服务器将从游戏板位置1开始。然后它将等待所有玩家收到HTTP消息或超时。答复将用于当前董事会职位的信息。因此,如果客户端最终发送2条消息,它将获得两个具有相同游戏无聊ID的回复。

每次从客户端获得连接时,都会发送一个线程来处理该消息,它将等待下一个连接。

问题:消息是在蛇形线程上处理的。如果所有玩家都回复了一条消息。什么是告诉主线程去下一个板块的最好方法?也许我只需要让它成为单线程?但是我担心一个bug会冻结服务器。

然后是超时的问题。

我的一个想法是在套接字上设置超时,所以如果没有建立连接,它将始终退出,然后可以检查超时或所有玩家是否已发送消息。

这是我在网络游戏中的第一次尝试,我假设有很多方法可以做到这一点。

泰德

2 个答案:

答案 0 :(得分:0)

这里有一些可能有用的代码。

// use an atomic integer so all threads can count their moves
AtomicInteger moveCounter = new AtomicInteger();

// main thread is in a loop
long timeoutMillis = System.currentTimeMillis() + MOVE_TIMEOUT_MILLIS;
while (moveCounter.get() < NUMBER_OF_CLIENTS) {
    synchronized (moveCounter) {
        // wait a second
        moveCounter.wait(timeoutMillis - System.currentTimeMillis());
    }
    if (System.currentTimeMillis() >= timeoutMillis) {
        // we timed out, break
        break;
    }
}
// now go ahead and process the move ...

每个客户端处理程序都会执行:

// read the move from the client ...
// store the move somewhere in the server...
moveCounter.decrementAndGet();
// exit

您可能应该使用Executors.newCachedThreadPool()或另一个线程池为每个客户端连接分叉处理程序。

希望这有帮助。

答案 1 :(得分:0)

我所做的是拥有一个主Server类,每个客户都有一个线程。该线程被添加到代表每个客户端的ArrayList Threads

然后,您可以让Server类遍历列表并检查值,例如hasMessage。如果每个都是真的,那么继续游戏。

这是一些廉价的代码:

//...Somewhere in the Server
ArrayList<Thread> clients = new ArrayList<Thread>();

public void addClient() {
  clients.add(new ClientThread());
}

public boolean checkForMessages() {
  for(Thread t : clients)
    if(!t.hasMessage)
      return false;
  return true;
}

ClientThread类处理与每个客户端的通话,每个客户端都有自己的线程。