view src/main/java/alice/daemon/Connection.java @ 419:aefbe41fcf12 dispose

change tab to space
author sugi
date Tue, 15 Jul 2014 16:00:22 +0900
parents aadea6a59376
children 2f2623484b77
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);

    }
}