view src/main/java/christie/daemon/Connection.java @ 126:c6e4d0e4954c

update datagear add shutdown
author akahori
date Tue, 18 Dec 2018 15:12:45 +0900
parents d92f0bbad1eb
children
line wrap: on
line source

package christie.daemon;

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

import christie.codegear.CodeGearManager;
import christie.datagear.command.Command;

public class Connection {

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

    public Connection(Socket socket, CodeGearManager cgm) {
        this.socket = socket;
        this.cgm = cgm;
    }

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

    }
    /*
    public void putConnectionInfo() {
        if (name!=null) {
            ConnectionInfo connectionInfo = new ConnectionInfo(name, socket);
            cgm.getLocalDGM().put("_DISCONNECT", connectionInfo);
            if (sendManager) {
                cgm.getDGM("manager").put("_DISCONNECTNODE", connectionInfo);
                sendManager = false;
            }
        }
    }*/

    public synchronized void write(Command cmd) {
        ByteBuffer buffer = cmd.convert();

        try {
            while (buffer.hasRemaining()) {
                socket.getChannel().write(buffer);
            }
            //System.out.println("write : " + cmd.key);

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

}