1. 程式人生 > >[分散式java]基於JavaAPI實現訊息方式的系統間通訊:TCP/IP+NIO

[分散式java]基於JavaAPI實現訊息方式的系統間通訊:TCP/IP+NIO

public class EchoProtocol implements Protocol {
    private int bufferSize;
    public EchoProtocol(int inBufferSize){
        this.bufferSize=inBufferSize;
    }
    @Override
    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel channel=((ServerSocketChannel)key.channel()).accept();
        //設定非阻塞
        channel.configureBlocking(false);
        //註冊該selector
        System.out.println("連線完畢,註冊Read事件");
        channel.
        register(key.selector(),SelectionKey.OP_READ, ByteBuffer.allocateDirect(bufferSize));
    }

    @Override
    public void handleRead(SelectionKey key) throws IOException {
        //取消對OP_READ事件的註冊
        key.interestOps(key.interestOps()&(~SelectionKey.OP_READ));
        SocketChannel channel= (SocketChannel) key.channel();
        ByteBuffer buffer=ByteBuffer.allocate(200);
        channel.read(buffer);
        String msg=new String(buffer.array());
        System.out.println("Server receive msg:"+msg);
        channel.register(key.selector(),SelectionKey.OP_WRITE);
    }

    @Override
    public void handleWrite(SelectionKey key) throws IOException {
        //取消對OP_READ事件的註冊
        //key.interestOps(key.interestOps()&(~SelectionKey.OP_WRITE));
        System.out.println("start send msg to client…");
        ByteBuffer buffer=ByteBuffer.wrap(new String("Hello,I am Server!").getBytes());
        SocketChannel channel= (SocketChannel) key.channel();
        long successedNum=channel.write(buffer);//向通道中寫資料
        System.out.println("endoff send msg to client,send successed char :"+successedNum);
    }
}
3、服務端主要類實現
public class TcpIpNioJavaMethod_Server {

    public static void main(String[] args) {
        new TcpIpNioJavaMethod_Server().createNioJavaMethodServer();
    }

    public void createNioJavaMethodServer(){
        //開啟一個Selector
        Selector selector=null;
        try {
            selector= Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //開啟一個Channel
        ServerSocketChannel listnChannel=null;
        try {
            listnChannel=ServerSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //繫結服務端埠
        try {
            listnChannel.socket().bind(new InetSocketAddress(1234));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //設定channel為非阻塞才可以註冊選擇器
        try {
            listnChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //註冊該selector,channel可以進行accept操作
        try {
            listnChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        }

        Protocol protocol=new EchoProtocol(256);

        while(true){
            try {
                System.out.println("阻塞等待感興趣的事~");
                if(selector.select(6000)==0){//等於0表示沒有Channel操作
                    continue;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
            while(keyIter.hasNext()){
                SelectionKey key=keyIter.next();
                keyIter.remove();//
                //處理accept事件
                if(key.isAcceptable()){
                    try {
                        System.out.println("handleAccept~");
                        protocol.handleAccept(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //處理讀事件
                if(key.isReadable()){
                    try {
                        System.out.println("handleRead~");
                        protocol.handleRead(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //處理寫事件
                if(key.isWritable()&&key.isValid()){
                    try {
                        System.out.println("handleWrite~");
                        protocol.handleWrite(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //keyIter.remove();
                //由於select()操作只是向Selector所關聯的鍵集合中新增元素
                //因此,如果不移除每個處理過的鍵,
                //它就會在下次呼叫select()方法時仍然保留在集合中
                //而且可能會有無用的操作來呼叫它。
            }
        }
    }
}
以上為簡單的個人實現,以下為詳細的說明: