view src/alice/daemon/OutboundTcpConnection.java @ 16:433e601a8e28

network bug fix
author kazz <kazz@cr.ie.u-ryukyu.ac.jp>
date Sun, 15 Jan 2012 12:17:30 +0900
parents e3f1b21718b0
children b5a21baf0b07
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 {
				CommandMessage cmdMsg = convert(connection.sendQueue.take());
				byte[] buf = msgpack.write(cmdMsg);
				ByteBuffer buffer = ByteBuffer.allocateDirect(4 + buf.length);
				buffer.putInt(buf.length);
				buffer.put(buf);
				buffer.flip();
				connection.socket.getChannel().write(buffer);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	
}