view src/main/java/alice/daemon/Connection.java @ 523:145c425db88d dispose

add CompressedLDSM
author Nozomi Teruya <e125769@ie.u-ryukyu.ac.jp>
date Thu, 09 Apr 2015 18:36:26 +0900
parents a7f140f4bcb1
children 061478079bc7
line wrap: on
line source

package alice.daemon;

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

import alice.datasegment.Command;
import alice.datasegment.DataSegment;
import alice.datasegment.ReceiveData;
import alice.datasegment.SendOption;

public class Connection {

    public Socket socket;
    public String name;
    public LinkedBlockingQueue<Command> sendQueue = new LinkedBlockingQueue<Command>();
    public boolean sendManager = true;

    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) {
        ByteBuffer buffer = cmd.convert();
        try {
            while (buffer.hasRemaining()) {
                socket.getChannel().write(buffer);
            }
        } catch (Exception e) { }
    }

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

    }

    public void putConnectionInfo() {
        if (name!=null){
            ConnectionInfo c = new ConnectionInfo(name, socket);
            ReceiveData rData = new ReceiveData(c, false, false);
            DataSegment.getLocal().put("_DISCONNECT", rData, null);
            if (sendManager) {
                SendOption option = new SendOption(false, false);
                DataSegment.get("manager").put("_DISCONNECTNODE", rData, option);
            }
        }

    }
}