view src/main/java/alice/daemon/Connection.java @ 345:8f71c3e6f11d

Change directory structure Maven standard
author sugi
date Wed, 16 Apr 2014 18:26:07 +0900
parents
children aadea6a59376
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;

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) {
			e.printStackTrace();
		}
	}
	
	public void close(){
		try {
			socket.shutdownOutput();
			socket.shutdownInput();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}