Java NIO 服务端和客户端

package com.cctv.http.nio;


import sun.security.action.GetPropertyAction;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Title:
 * @BelongProjecet http-demo
 * @Description:
 * @Author: lingchuan
 * @Date: 2020-04-27 16:09
 */
public class NioHttpServer {

    public static volatile ConcurrentMap<Channel, String> req = new ConcurrentHashMap();

    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080), 1024);
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            int result = selector.selectNow();
            if (result == 0) {
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = it.next();
                handleInput(selectionKey);
                it.remove();
            }
        }


    }

    private static void handleInput(SelectionKey key) throws IOException {


        if (key.isAcceptable()) {
            doAccep(key);
        }
        if (key.isReadable()) {
            doRead(key);
        }
        if (key.isWritable()) {
            doWrite(key);
        }
    }

    private static void doAccep(SelectionKey key) throws IOException {
        SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
        channel.configureBlocking(false);
        channel.register(key.selector(), SelectionKey.OP_READ);
    }

    private static void doRead(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();

        ByteBuffer buffer = ByteBuffer.allocate(4);
        String requestData = "";
        int eof = channel.read(buffer);
        System.out.println("读入" + eof + "字节");
        if (eof > 0) {
            buffer.flip();
            CharBuffer cb = Charset.forName("UTF-8").decode(buffer);
            requestData += cb.toString();
            buffer.clear();
            if (key.attachment() != null) {
                key.attach(key.attachment() + requestData);
            } else {
                key.attach(requestData);
            }
        } else {
            System.out.println("读完毕");
            key.interestOps(SelectionKey.OP_WRITE);
        }
    }

    private static void doWrite(SelectionKey key)
            throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("200 OK\n");
        stringBuffer.append("Content-Type: text/html; charset=UTF-8\n");
        stringBuffer.append("Received:" + key.attachment());
        stringBuffer.append("\n");
        String response = stringBuffer.toString();
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }
        key.cancel();
        channel.close();
    }
}
package com.cctv.http.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @Title:
 * @BelongProjecet http-demo
 * @BelongPackage com.cctv.http.nio
 * @Description:
 * @Copyright CCTV.com
 * @Author: lingchuan
 * @Date: 2020-05-12 17:06
 */
public class NioClient {
    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));

        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            int result = selector.selectNow();
            if (result == 0) {
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = it.next();
                handleInput(selectionKey);
                it.remove();
            }
        }
    }

    private static void handleInput(SelectionKey key) throws IOException {
        if (key.isConnectable()) {
            SocketChannel channel = (SocketChannel) key.channel();
            System.out.println(channel.finishConnect());
            key.interestOps(SelectionKey.OP_WRITE);
        }
        if (key.isAcceptable()) {
        }
        if (key.isReadable()) {
            doRead(key);
        }
        if (key.isWritable()) {
            doWrite(key);
            key.interestOps(SelectionKey.OP_READ);
        }
    }

    private static void doRead(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();

        ByteBuffer buffer = ByteBuffer.allocate(4);
        String requestData = "";

        int eof = channel.read(buffer);
        if (eof >= 0) {
            System.out.println("继续读:" + eof);
            buffer.flip();
            CharBuffer cb = Charset.forName("UTF-8").decode(buffer);
            requestData += cb.toString();
            buffer.clear();
            if (key.attachment() != null) {
                key.attach(key.attachment() + requestData);
            } else {
                key.attach(requestData);
            }

        }
        if (eof == -1) {
            System.out.println(key.attachment());
            if (key.isValid()) {
                key.cancel();
                channel.close();
                System.exit(1);
            }
        }
    }

    private static void doWrite(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        byte[] req = "Hello Server".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        socketChannel.shutdownOutput();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值