view src/alice/daemon/OutboundTcpConnection.java @ 100:b01fb5090e28 working

add default code to each case statements
author kazz <kazz@cr.ie.u-ryukyu.ac.jp>
date Thu, 28 Jun 2012 01:50:29 +0900
parents d4c7f7b1096b
children d5d9ca4cbe87
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);
	}
	
	/**
	 * pipeline thread for transmission
	 */
	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;
				default:
					break;
				}
				CommandMessage cmdMsg = convert(cmd);
				ByteBuffer buffer = ByteBuffer.wrap(msgpack.write(cmdMsg));
				while (buffer.hasRemaining()) {
					connection.socket.getChannel().write(buffer);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}