view src/main/java/alice/daemon/Connection.java @ 458:bcf6f4a6fcd0 dispose

need set Meta DataSegment PUT API
author sugi
date Mon, 03 Nov 2014 17:12:53 +0900
parents b004f62b83e5
children 6e304a7a60e7
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.datasegment.Command;
import alice.datasegment.DataSegment;
import alice.datasegment.ReceiveData;

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) {	
        ByteBuffer buffer = cmd.convert();
        try {
            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());
        ReceiveData rData = new ReceiveData(c, false, false);
        DataSegment.getLocal().put("disconnect", rData, null);

    }
}