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

import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import org.json.JSONObject;
import org.json.JSONException;

import java.util.Arrays;

public class VibeDumb implements Communicator {
	public static final byte[] MAGIC = new byte[]{ 1, 3, 3, 7 };

	private Connector conn;
	private DataInputStream inStream;
	private DataOutputStream outStream;

	public VibeDumb(Connector c) {
		conn = c;
	}

	public void sendMsg(Message m) throws IOException {
		if(outStream == null) {
			outStream = conn.getOutputStream();
		}
		byte version = 0;
		byte msgType = m.getMsgType();
		byte[] unused = new byte[]{ 0, 0 };
		String msg = m.toJsonString();
		outStream.write(MAGIC);
		outStream.write(version);
		outStream.write(msgType);
		outStream.write(unused);
		outStream.writeUTF(msg);
	}
	public Message receiveMsg() throws IOException {
		if(inStream == null) {
			inStream = conn.getInputStream();
		}
		byte[] magic = new byte[4];
		byte version = 0;
		byte msgType = 0;
		byte[] unused = new byte[2];
		inStream.read(magic);
		if(!isMagicCorrect(magic)) {
			throw new InternalHanabiError(); // TODO
		}
		version = inStream.readByte();
		switch(version) {
		case 0: // TODO magic number?
			break;
		default:
			throw new InternalHanabiError(); // TODO
		}
		msgType = inStream.readByte();
		inStream.read(unused);
		String msg = inStream.readUTF(); // TODO ddos?
		if(msg == null) throw new InternalHanabiError(); // TODO
		try {
			Message m;
			if(msg.equals("")) {
				m = new Message(msgType);
			} else {
				JSONObject jo = new JSONObject(msg);
				m = new Message(jo);
				m.setMsgType(msgType);
			}			
			return m;
		} catch(JSONException ex) {
			throw new InternalHanabiError(ex);
		}
	}
	public void establish() throws IOException {
		// FIXME
		conn.establishConnection();
	}
	private static boolean isMagicCorrect(byte[] magic) {
		return Arrays.equals(MAGIC, magic);
	}

	@Override
	public Connector getConnector() {
		return conn;
	}
}