SOA研究(1)-从NIO开始

原创 2016年05月31日 20:34:25

最近在看dubbo源码,觉得dubbo还是设计很优秀。有个想法模拟dubbo去写一个SOA框架。编写SOA框架,首先要解决底层传输问题,虽然dubbo默认是用netty传输,但是也是基于NIO。所以我自己写了NIO编程实例,开始研究SOA之路。

实现功能很简单,client发送消息给server,server接收后又发消息给client。

server端:


public class NIOServer extends Thread {
    private Selector selector;
    private int port;
    public NIOServer() {
    }
    public NIOServer(int port) throws IOException {
        this.port = port;
    }
    public void run() {
        System.out.println("服务端线程已经启动!");
        try {
            while (selector.select() > 0) {
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeySet.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    try {
                        if (key.isAcceptable()) {
                            doAccept(key);
                        }
                        if (key.isReadable()) {
                            doRead(key);
                        }
                        if (key.isWritable()) {
                            doWrite(key);
                        }
                    } catch (ClosedSelectorException cek) {
                        cek.printStackTrace();
                    } catch (CancelledKeyException ck) {
                        ck.printStackTrace();
                        key.cancel();
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(selector != null){
                selector.close();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    private void doAccept(SelectionKey key) throws IOException {
        System.out.println("accept...");
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        SocketChannel channel = server.accept();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_READ);
    }
    private void doRead(SelectionKey key) throws IOException {
        System.out.println("read data from client...");
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            while (channel.read(buffer) > 0) {
                buffer.flip();
                System.out.println(getString(buffer));
                buffer.clear();
            }
            channel.register(selector, SelectionKey.OP_WRITE);
        } catch (Throwable e) {
            e.printStackTrace();
            key.cancel();
        }
    }
    private void doWrite(SelectionKey key) throws IOException {
        System.out.println("write data to client...");
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.wrap(new String("Hi, client").getBytes("UTF-8"));
        try {
            while (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            channel.register(selector, SelectionKey.OP_READ);
        } catch (Throwable e) {
            e.printStackTrace();
            key.cancel();
        }
    }
    public void initServer(int port) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(port));
        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
    public void stopServer() throws IOException {
        if (!selector.isOpen()) {
            selector.close();
        }
    }
    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        try {
            server.initServer(8859);
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
            server.stopServer();
        }
    }
}

client端:


public class NIOClient extends Thread {
    private Selector selector;
    private void initClient(int port) throws IOException {
        InetSocketAddress address = new InetSocketAddress(port);
        selector = Selector.open();
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_CONNECT);
        channel.connect(address);
    }
    public void run() {
        System.out.println("客户端已经启动!");
        try {
            while (selector.select() > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isConnectable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        // 如果正在连接,则完成连接
                        if (channel.isConnectionPending()) {
                            channel.finishConnect();
                        }
                        channel.register(selector, SelectionKey.OP_WRITE);
                    }
                    if (key.isReadable()) {
                        doRead(key);
                    }
                    if(key.isWritable()){
                        doWrite(key);
                    }
                }
            }
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void doRead(SelectionKey key) throws IOException {
        System.out.println("read data from server...");
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (channel.read(buffer) > 0) {
            buffer.flip();
            System.out.println(getString(buffer));
            buffer.clear();
        }
        channel.register(selector, SelectionKey.OP_WRITE);
    }
    private void doWrite(SelectionKey key) throws IOException {
        System.out.println("write data to server...");
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.wrap(new String("Hi, server").getBytes("UTF-8"));
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
        channel.register(selector, SelectionKey.OP_READ);
    }
    public void stopServer() throws IOException {
        if (selector != null && selector.isOpen()) {
            selector.close();
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        NIOClient client = new NIOClient();
        try {
            client.initClient(8859);
            client.start();
        } catch (Exception e) {
            client.stopServer();
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

windows 32位系统中进程最大可用内存空间为3GB

windows 32位系统中进程最大可用内存空间为3GB (转) http://msdn.microsoft.com/zh-cn/library/ms189334.aspx 进程地址空间 ...

Java对象指针压缩

通常64位JVM消耗的内存会比32位的大1.5倍,这是因为对象指针在64位架构下,长度会翻倍(更宽的寻址)。 对于那些将要从32位平台移植到64位的应用来说,平白无辜多了1/2的内存占用,这是开发者不...

SOA研究(3)-RPC的第二次尝试

在之前的文章里面,我们实现了简单的RPC调用,通过不断发消息,然后接收消息,显然它还不算真正的RPC调用。设计思路这次我们对它进行改进,模仿dubbo,定义Invoker类,它代表可以执行的实体。定义...

SOA研究-用zookeeper实现服务的注册和发现

注册中心一般具有以下功能: 注册服务 订阅服务 失败重新注册和订阅 本地缓存服务信息列表 大体过程如下: 1.服务提供者暴露服务后向注册中心注册,如果多个注册中心的话,需要分别注册到多个注册中心;注册...

SOA研究(2)-第一个RPC例子

我们还是用NIO通信,client建立连接后不断向server发送对象Invocation。需要远端调用的方法,这里演示发送“foo”参数,服务端传回来”Fello foo”. public clas...

中国SOA标准体系研究报告

  • 2015年12月02日 13:49
  • 699KB
  • 下载

淘宝SOA框架dubbo学习(1)--first demo

部署开发,需要三部分:服务提供者、服务容器、服务消费者 本人用 eclipse 开发 1、服务提供者jar生成 A、项目截图 B、源码: ? ...
  • xwnxwn
  • xwnxwn
  • 2016年03月26日 16:30
  • 414
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:SOA研究(1)-从NIO开始
举报原因:
原因补充:

(最多只允许输入30个字)