IO与NIO对于异步Socket的处理

以下的内容以代码为主,简单的展示了传统IO流和NIO流对Socket请求的处理。

简单来说,传统IO流想要处理多个客户端的Socket请求,它必须要不断的创建新的线程来专门为连入的Socket请求进行处理,如果连入的Socket请求很多,并且来自不同的IP或者端口就必须要不断的创建线程,对系统资源会造成很大的占用。

下面就是传统IO流异步处理Socket请求的代码:

package com.firstdata.IOSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketCase {

    public static final int Port = 4495;
    public static ServerSocket server = null;

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        init();
        System.out.println("Finish init!");
        while (true) {
            Socket socket = server.accept();
            System.out.println("Client connected!" + socket.getPort());
            try {
                SocketProcess socketProcess = new SocketProcess(socket);
                System.out.println("Start thread!");
                // Thread thread = new Thread(socketCase);
                Thread thread = new Thread(socketProcess);
                thread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    private static void init() throws IOException {
        server = new ServerSocket();
        server.setSoTimeout(0);
        server.setReuseAddress(true);
        server.bind(new InetSocketAddress(4495));

    }

}

除了上面这个主函数和初始化方法,还需要下面这个实现多线程的类:

package com.firstdata.IOSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketProcess implements Runnable {

    private static Socket socket = null;

    public SocketProcess(Socket socket) {
        SocketProcess.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            handlerSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void handlerSocket() {
        InputStream rd = null;
        OutputStream bw = null;
        try {
            rd = getBufferedReader(socket);
            bw = getBufferedWriter(socket);
            byte[] ReqBuff = new byte[1000];
            System.out.println("Ready receive the request message!");
            while (rd.read(ReqBuff) > 0) {
                System.out.println("start");
                System.out.println(new String(ReqBuff));
                System.out.println("finish");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                rd.close();
                bw.close();
                socket.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    private static InputStream getBufferedReader(Socket socket) throws IOException {
        InputStream in = socket.getInputStream();
        return in;
    }

    private static OutputStream getBufferedWriter(Socket socket) throws IOException {
        OutputStream out = socket.getOutputStream();
        return out;
    }

}

有上面2个类就能够构成一个简单的异步Socket服务端类

对于NIO而已,NIO会有一个选择器的出现,有点类似在传统IO流的处理之后加上一块分配数据流的工作,这样能够使得Socket在不创建线程的任务下处理多个来自不同地方的Socket请求,对于NIO原理的介绍,网上有很多很多,下面是个简单的NIO类:

package com.firstdata.NIOSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SocketCase {

    // 通道管理器
    private Selector selector;

    /**
     * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
     * 
     * @param port 绑定的端口号
     * @throws IOException
     */
    public void initServer(int port) throws IOException {
        // 获得一个ServerSocket通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        // 设置通道为非阻塞
        serverChannel.configureBlocking(false);
        // 将该通道对应的ServerSocket绑定到port端口
        serverChannel.socket().bind(new InetSocketAddress(port));
        // 获得一个通道管理器
        this.selector = Selector.open();
        // 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
        // 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("OP_ACCEPT");
    }

    /**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     * 
     * @throws IOException
     */
    public void listen() {
        System.out.println("服务端启动成功!");
        // 轮询访问selector
        while (true) {
            // 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
            try {
                selector.select();
                // 获得selector中选中的项的迭代器,选中的项为注册的事件
                Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
                while (ite.hasNext()) {
                    SelectionKey key = (SelectionKey) ite.next();
                    // 删除已选的key,以防重复处理
                    ite.remove();
                    // 客户端请求连接事件
                    if (key.isAcceptable()) {
                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        // 获得和客户端连接的通道
                        SocketChannel channel = server.accept();
                        // 设置成非阻塞
                        channel.configureBlocking(false);

                        // 在这里可以给客户端发送信息哦
                        channel.write(ByteBuffer.wrap(new String("向客户端发送了一条信息").getBytes()));
                        // 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
                        channel.register(this.selector, SelectionKey.OP_READ);

                        // 获得了可读的事件
                    } else if (key.isReadable()) {
                        read(key);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理读取客户端发来的信息 的事件
     * 
     * @param key
     * @throws IOException
     */
    public void read(SelectionKey key) throws IOException {
        try {
            // 服务器可读取消息:得到事件发生的Socket通道
            SocketChannel channel = (SocketChannel) key.channel();
            // 创建读取的缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(100);
            int statusCode = channel.read(buffer);
            System.out.println("length:" + statusCode);
            if (statusCode != -1) {
                byte[] data = buffer.array();
                String msg = new String(data).trim();
                System.out.println("服务端收到信息:" + msg);
                ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
                channel.write(outBuffer);// 将消息回送给客户端
            } else {
                channel.close();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 启动服务端测试
     * 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        SocketCase server = new SocketCase();
        server.initServer(4495);
        server.listen();
    }

}

本人只是代码的搬运工以及测试员。





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值