Net2QRunnable.java :  » Game » inequity » network » Java Open Source

Java Open Source » Game » inequity 
inequity » network » Net2QRunnable.java
package network;

import java.io.*;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import packets.CommandRequest;
import packets.PlayerQuitReq;

/**
 * Listens on network and drops packets to queue for processing
 * @author Joel Garboden
 */
class Net2QRunnable implements Runnable
{
  Server loggingServer;

  private int ID;
  private boolean active;

  private ObjectInputStream netIn;

  private PriorityBlockingQueue<CommandRequest> srvQ;

  /**
   * Constructor for lobby mode
   * @param netIn incoming network stream
   * @param srvQ queue to drop packets to for processing
   */
  public Net2QRunnable(ObjectInputStream netIn, PriorityBlockingQueue<CommandRequest> srvQ)
  {
    this.ID = -3;
    active = true;
    this.netIn = netIn;
    this.srvQ = srvQ;
  }

  /**
   * Constructor for game mode
   * @param ID client ID
   * @param netIn incoming network stream
   * @param srvQ queue to drop packets to for processing
   */
  public Net2QRunnable(int ID, ObjectInputStream netIn, PriorityBlockingQueue<CommandRequest> srvQ)
  {
    this(netIn, srvQ);
    this.ID = ID;
  }

  /**
   * Enables logging to current server
   * @param server server to dump logs to
   */
  public void setLoggingServer(Server server)
  {
    loggingServer = server;
  }

  /**
   * Mutator
   * @param active activity state
   */
  public void setActive(boolean active)
  {
    this.active = active;
  }

  /**
   * Accessor
   * @return activity state
   */
  public boolean isActive()
  {
    return active;
  }

  /**
   * Continuously listens on incoming network stream for packets, <br/>
   * and drops them to the server queue
   */
  public void run()
  {
    CommandRequest cmdreq;
    try
    {
      try
      {
        while(active)
        {
          cmdreq = (CommandRequest)netIn.readObject();
          srvQ.add(cmdreq);
          if(loggingServer != null)
            loggingServer.postLogMsg("Recieving: " + ID + " " + cmdreq.toString());
          else
            System.out.println("Recieving: " + ID + " " + cmdreq.toString());
        }

      }
      catch (EOFException e)
      {
        srvQ.add(new PlayerQuitReq(ID));
        System.out.println("Net2QRunnable inner: " + e);
        this.finalize();
        return;
      }

    }
    catch (IOException e)
    {
      System.out.println("Net2QRunnable outer: " + e);
    }
    catch (Throwable ex)
    {
      Logger.getLogger(Net2QRunnable.class.getName()).log(Level.SEVERE, "Net2QRunnable throwable", ex);
    }
    srvQ.add(new PlayerQuitReq(ID));
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.