view src/alice/daemon/OutboundTcpConnection.java @ 218:d50cddf64396 working

TestRemoteAlice works
author sugi
date Wed, 27 Mar 2013 20:35:08 +0900
parents 1044a79ce4ef
children 2a8bcf09bd06
line wrap: on
line source

package alice.daemon;

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

import alice.codesegment.SingletonMessage;
import alice.datasegment.Command;

public class OutboundTcpConnection extends Thread {
	
	public Connection connection;
	
	public OutboundTcpConnection(Connection connection) {
		this.connection = connection;
	}
	
	public CommandMessage convert(Command cmd) {
		if (cmd.val==null&&cmd.obj!=null){
			try {
				cmd.val = SingletonMessage.getInstance().unconvert(cmd.obj);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new CommandMessage(cmd.type.id, cmd.index, cmd.seq, cmd.key, cmd.val);
	}
	
	/**
	 * pipeline thread for transmission
	 */
	public void run() {
		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(SingletonMessage.getInstance().write(cmdMsg));
				while (buffer.hasRemaining()) {
					connection.socket.getChannel().write(buffer);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}