view src/main/java/alice/daemon/Connection.java @ 641:646f705e65b1

setkey on remote
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Sun, 31 Dec 2017 01:08:52 +0900
parents b3c9554ccb1b
children
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);
            DataSegment.getLocal().put("_DISCONNECT", rData, false);
            if (sendManager) {
                DataSegment.get("manager").put("_DISCONNECTNODE", rData, false);
                sendManager = false;
            }
        }

    }
}