码迷,mamicode.com
首页 > 其他好文 > 详细

NIO Socket编程实例

时间:2016-07-16 14:15:09      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

  NIOUtil类,用来通过SOcket获取BufferedReader和PrintWriter。

技术分享
package IO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class NIOUtil {
    public static PrintWriter getPrintWriter(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        return new PrintWriter(outputStream, true);
    }

    public static BufferedReader getBufferedReader(Socket socket)
            throws IOException {
        InputStream inputStream = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(inputStream));
    }
}
View Code

  使用ServerSocketChannel创建阻塞服务器端程序:

技术分享
package IO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BlockingNIOServer {
    private int port = 8000;
    private ServerSocketChannel serverSocketChannel = null;
    private ExecutorService executorService = null;
    private static int DEFAULT_POOI_SIZE = 4;

    public BlockingNIOServer() throws IOException {
        super();
        this.executorService = Executors.newFixedThreadPool(DEFAULT_POOI_SIZE
                * Runtime.getRuntime().availableProcessors());
        this.serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().setReuseAddress(true);
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        this.executorService = executorService;
    }

    public void service() {
        while (true) {
            SocketChannel channel = null;
            try {
                channel = serverSocketChannel.accept();
                executorService.execute(new Handler(channel));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new BlockingNIOServer().service();
    }

    private class Handler implements Runnable {
        private SocketChannel channel;
        public Handler(SocketChannel channel) {
            super();
            this.channel = channel;
        }

        @Override
        public void run() {
            handler(channel);
        }

        public void handler(SocketChannel channel) {
            Socket socket = null;
            try {
                socket = channel.socket();
                System.out.println("接收到来自:" + socket.getInetAddress() + " 端口:"
                        + socket.getPort() + "的请求");
                BufferedReader bufferedReader = NIOUtil
                        .getBufferedReader(socket);
                PrintWriter printWriter = NIOUtil.getPrintWriter(socket);
                String msg = null;

                while ((msg = bufferedReader.readLine()) != null) {
                    System.out.println(msg);
                    printWriter.println(Echo(msg));
                    if ("bye".equalsIgnoreCase(msg))
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        private String Echo(String msg) {
            return "ECHO:" + msg;
        }
    }
}
View Code

  使用SocketChannel创建阻塞Socket客户端:

技术分享
package IO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BlockingNIOServer {
    private int port = 8000;
    private ServerSocketChannel serverSocketChannel = null;
    private ExecutorService executorService = null;
    private static int DEFAULT_POOI_SIZE = 4;

    public BlockingNIOServer() throws IOException {
        super();
        this.executorService = Executors.newFixedThreadPool(DEFAULT_POOI_SIZE
                * Runtime.getRuntime().availableProcessors());
        this.serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().setReuseAddress(true);
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        this.executorService = executorService;
    }

    public void service() {
        while (true) {
            SocketChannel channel = null;
            try {
                channel = serverSocketChannel.accept();
                executorService.execute(new Handler(channel));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new BlockingNIOServer().service();
    }

    private class Handler implements Runnable {
        private SocketChannel channel;
        public Handler(SocketChannel channel) {
            super();
            this.channel = channel;
        }

        @Override
        public void run() {
            handler(channel);
        }

        public void handler(SocketChannel channel) {
            Socket socket = null;
            try {
                socket = channel.socket();
                System.out.println("接收到来自:" + socket.getInetAddress() + " 端口:"
                        + socket.getPort() + "的请求");
                BufferedReader bufferedReader = NIOUtil
                        .getBufferedReader(socket);
                PrintWriter printWriter = NIOUtil.getPrintWriter(socket);
                String msg = null;

                while ((msg = bufferedReader.readLine()) != null) {
                    System.out.println(msg);
                    printWriter.println(Echo(msg));
                    if ("bye".equalsIgnoreCase(msg))
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        private String Echo(String msg) {
            return "ECHO:" + msg;
        }
    }
}
View Code

 

NIO Socket编程实例

标签:

原文地址:http://www.cnblogs.com/wxgblogs/p/5676052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!