Newer
Older
hanabi-networking / src / server / Client.java
package server;

import java.io.IOException;

public class Client extends Thread {
	BaseGame game;
	Communicator comm;
	int id;
	boolean isReady;
	volatile boolean keepRunning;
	Client(BaseGame game, Communicator c, int id) {
		this.game = game;
		comm = c;
		this.id = id;
		isReady = false;
		keepRunning = false;
	}

	Client(BaseGame game, Connector conn, byte proto, boolean isServer, int id) {
		this(game, ctorHelper(conn, proto, isServer, id), id);
	}
	
	private static Communicator ctorHelper(Connector conn, byte proto, boolean isServer, int id) {
		Communicator comm = null;
		switch(proto) {
		case ServerGame.PROTO_VIBE_DUMB:
			if(isServer) {
				comm = new ServerGame.VibeDumbServer(conn, id);
			} else {
				comm = new VibeDumb(conn);
			}
			break;
		default:
			throw new InternalHanabiError(); // TODO
		}
		return comm;
	}
	
	void stopListening() { keepRunning = false; }
	
	@Override
	public void run() {
		keepRunning = true;
		boolean retry = true;
		do {
			try {
				comm.establish();
				break;
			} catch(IOException ex) {
				retry = game.handleIOException(ex);
			}
		} while(retry);
		listen();
	}
	
	private void listen() {
		while(keepRunning) {
			Message m = null;
			boolean retry = true;
			while(retry){
				try {
					m = comm.receiveMsg();
					break;
				} catch(IOException ex) {
					retry = game.handleIOException(ex);
					if(!keepRunning) return;
				}
			}
			game.processMsg(m);
		}
	}
	
	public int getOrigin() { return id; }
	public void setOrigin(int newId) { id = newId; } // TODO: remove this method? 
}