博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java nio
阅读量:5098 次
发布时间:2019-06-13

本文共 6445 字,大约阅读时间需要 21 分钟。

1、Java Socket Clientpublic class PlainEchoClient {    public static void main(String args[]) throws Exception {        for (int i = 0; i < 20; i++) {            startClientThread();        }    }    private static void startClientThread() throws UnknownHostException,            IOException {        Thread t = new Thread(new Runnable() {            @Override            public void run() {                try {                    startClient();                } catch (Exception e) {                    e.printStackTrace();                }            }        });        t.start();    }    private static void startClient() throws UnknownHostException, IOException {        long beforeTime = System.nanoTime();        String host = "127.0.0.1";        int port = 8086;        Socket client = new Socket(host, port);        // 建立连接后就可以往服务端写数据了        Writer writer = new OutputStreamWriter(client.getOutputStream());        writer.write("Hello Server.");        writer.flush();        // 写完以后进行读操作        Reader reader = new InputStreamReader(client.getInputStream());        char chars[] = new char[64];// 假设所接收字符不超过64位,just for demo        int len = reader.read(chars);        StringBuffer sb = new StringBuffer();        sb.append(new String(chars, 0, len));        System.out.println("From server: " + sb);        writer.close();        reader.close();        client.close();        System.out.println("Client use time: "                + (System.nanoTime() - beforeTime) + " ns");    }}2、IO Socket Server这个Socket Server模拟的是我们经常使用的thread-per-connection模式, Tomcat,JBoss等Web Container都是这种方式。public class PlainEchoServer {    private static final ExecutorService executorPool = Executors.newFixedThreadPool(5);    private static class Handler implements Runnable{        private Socket clientSocket;        public Handler(Socket clientSocket){            this.clientSocket = clientSocket;        }        @Override        public void run() {            try {                BufferedReader reader = new BufferedReader(                        new InputStreamReader(                                clientSocket.getInputStream()));                PrintWriter writer = new PrintWriter(                        clientSocket.getOutputStream(), true);                char chars[] = new char[64];                int len = reader.read(chars);                StringBuffer sb = new StringBuffer();                sb.append(new String(chars, 0, len));                System.out.println("From client: " + sb);                writer.write(sb.toString());                writer.flush();            } catch (IOException e) {                e.printStackTrace();                try {                    clientSocket.close();                } catch (IOException ex) {                    // ignore on close                }            }        }    }           public void serve(int port) throws IOException {        final ServerSocket socket = new ServerSocket(port);        try {            while (true) {                long beforeTime = System.nanoTime();                final Socket clientSocket = socket.accept();                System.out.println("Establish connection time: "+ (System.nanoTime()-beforeTime)+" ns");                executorPool.execute(new Handler(clientSocket));            }        } catch (IOException e) {            e.printStackTrace();        }    }    public static void main(String[] args) throws IOException{        PlainEchoServer server = new PlainEchoServer();        server.serve(8086);    }}3、NIO Socket Serverpublic class PlainNioEchoServer {    public void serve(int port) throws IOException {        ServerSocketChannel serverChannel = ServerSocketChannel.open();        ServerSocket ss = serverChannel.socket();        InetSocketAddress address = new InetSocketAddress(port);        ss.bind(address); // #1        serverChannel.configureBlocking(false);        Selector selector = Selector.open();        serverChannel.register(selector, SelectionKey.OP_ACCEPT); // #2        while (true) {            try {                selector.select(); // #3            } catch (IOException ex) {                ex.printStackTrace();                // handle in a proper way                break;            }            Set readyKeys = selector.selectedKeys(); // #4            Iterator iterator = readyKeys.iterator();            while (iterator.hasNext()) {                SelectionKey key = (SelectionKey) iterator.next();                try {                    if (key.isAcceptable()) {                        ServerSocketChannel server = (ServerSocketChannel) key                                .channel();                        long beforeTime = System.nanoTime();                        SocketChannel client = server.accept(); // #6                                               System.out.println("Accept connection time: "+ (System.nanoTime()-beforeTime)+" ns");                        if (client == null){
//Check if socketChannel has been created, it could be null, because it's non-blocking continue; } client.configureBlocking(false); client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, ByteBuffer.allocate(100)); } if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer output = (ByteBuffer) key.attachment(); client.read(output); } if (key.isWritable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer output = (ByteBuffer) key.attachment(); output.flip(); client.write(output); output.compact(); } } catch (IOException ex) { key.cancel(); try { key.channel().close(); } catch (IOException cex) { } } iterator.remove(); // #5 } } } public static void main(String[] args) throws IOException{ PlainNioEchoServer server = new PlainNioEchoServer(); server.serve(8086); }}

 

转载于:https://www.cnblogs.com/sidesky/p/6322381.html

你可能感兴趣的文章
Centos 添加SWAP(交换分区)
查看>>
SQLPlus的两种登录方式的不同效果
查看>>
《算法导论》CLRS算法C++实现(一)P11 插入排序
查看>>
ZROI2018暑期集训B班训练赛#1解题报告
查看>>
ListIterator
查看>>
HDU 2855 Fibonacci Check-up 矩阵
查看>>
Matlab使用xlsread, xlswrite函数导致excel进程无法终止的问题
查看>>
scrapy爬取数据的基本流程及url地址拼接
查看>>
Python 生产者和消费者模型
查看>>
GLSL中 Billboard和Point的顶点空间变换
查看>>
Fiddler基本用法:手机抓包
查看>>
poj 1328 Radar Installation 排序贪心
查看>>
数组与字符串 1.6
查看>>
信用卡还款项目(同事封装的ajax)
查看>>
java基本概念
查看>>
Struts2学习笔记(六) 结果(Result)(上)
查看>>
ajax提交写法
查看>>
Java编程语言基础 第三章 if嵌套分支用法
查看>>
判断质数的方法
查看>>
安全和共享设置
查看>>