view src/main/java/alice/daemon/Connection.java @ 417:aadea6a59376 dispose

create MetaCodeSegment use reflection
author sugi
date Tue, 15 Jul 2014 00:06:10 +0900
parents 8f71c3e6f11d
children aefbe41fcf12
line wrap: on
line source

package alice.daemon;

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

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

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 (ClosedChannelException e) {
			// when put dataSegment to remote if connection close this dataSemgent put.
			putConnectionInfo();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close(){
		try {
			socket.shutdownOutput();
			socket.shutdownInput();
			socket.close();
		} catch (ClosedChannelException e) {
			putConnectionInfo();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public void putConnectionInfo() {
		ConnectionInfo c = new ConnectionInfo(socket.getInetAddress().toString() ,socket.getPort());
		DataSegment.getLocal().put("disconnect", c);
		
	}
}