view src/alice/daemon/Connection.java @ 267:fac206b7849c

create Send/Receive Error class
author sugi
date Sat, 17 Aug 2013 18:55:19 +0900
parents 2a8bcf09bd06
children 23e53aaa8720
line wrap: on
line source

package alice.daemon;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;

import alice.codesegment.SingletonMessage;
import alice.datasegment.Command;
import alice.topology.HostMessage;
import alice.topology.manager.reconnection.SendError;

public class Connection {

	public Socket socket;
	public LinkedBlockingQueue<Command> sendQueue = new LinkedBlockingQueue<Command>();
	
	public Connection(Socket socket) {
		this.socket = socket;
	}
	
	public Connection() { }

	public void sendCommand(Command cmd) {
		try {
			sendQueue.put(cmd);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public String getInfoString() {
		return socket.getInetAddress().getHostName()
			   + ":" + socket.getPort();
	}

	public synchronized void write(Command cmd) {	
		CommandMessage cmdMsg = cmd.convert();
		ByteBuffer buffer;
		try {
			buffer = ByteBuffer.wrap(SingletonMessage.getInstance().write(cmdMsg));
			while (buffer.hasRemaining()) {
				socket.getChannel().write(buffer);
			}
		} catch (IOException e) {
			new SendError(new HostMessage(socket.getInetAddress().getHostName(), socket.getPort())).execute();
		}
	}

}