view src/alice/daemon/OutboundTcpConnection.java @ 51:919389066887

change protocol header: remove an integer representing message length (work?)
author kazz <kazz@cr.ie.u-ryukyu.ac.jp>
date Sun, 05 Feb 2012 06:26:26 +0900
parents cc440cb8582e
children ebdcab7b9b04
line wrap: on
line source

package alice.daemon;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.msgpack.MessagePack;

import alice.datasegment.Command;

public class OutboundTcpConnection extends Thread {
	
	public Connection connection;
	
	public OutboundTcpConnection(Connection connection) {
		this.connection = connection;
	}
	
	public CommandMessage convert(Command cmd) {
		return new CommandMessage(cmd.type.id, cmd.index, cmd.seq, cmd.key, cmd.val);
	}
	
	public void run() {
		MessagePack msgpack = new MessagePack();
		while (true) {
			try {
				Command cmd = connection.sendQueue.take();
				switch (cmd.type) {
				case CLOSE:
					connection.socket.close();
					return;
				case FINISH:
					System.exit(0);
					return;
				}
				CommandMessage cmdMsg = convert(cmd);
				byte[] buf = msgpack.write(cmdMsg);
				ByteBuffer buffer = ByteBuffer.allocateDirect(buf.length);
				buffer.put(buf);
				buffer.flip();
				while (buffer.hasRemaining()) {
					connection.socket.getChannel().write(buffer);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}