3.Netty之一个基于NIO的服务端

看了一下《Java NIO》这本书,然后尝试着写了一个服务端demo

package com.bj58.pn.nio;

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 NonIOServer implements Runnable {
	Selector selector;

	public NonIOServer(int port) throws IOException {
		// 0.开启selector监听器
		selector = Selector.open();
		// 1.开启通道
		ServerSocketChannel ssc = ServerSocketChannel.open();
		// 2.通道监听端口
		ssc.bind(new InetSocketAddress(port));
		// 3.设置通道属性(非阻塞)
		ssc.configureBlocking(Boolean.FALSE);
		// 4.注册到selector选择器
		ssc.register(selector, SelectionKey.OP_ACCEPT);
	}

	@Override
	public void run() {
		while (true) {
			try {
				// 1.开始监听
				selector.select();
				// 2.获取多路复用器选择的结果集
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();
				while (it.hasNext()) {
					SelectionKey key = it.next();
					it.remove();
					if (key.isValid() && key.isAcceptable()) {
						doAccept(key);
					}
					if (key.isValid() && key.isReadable()) {
						doRead(key);
					}
					if (key.isValid() && key.isWritable()) {
						doWrite(key);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void doAccept(SelectionKey key) {
		try {
			SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
			sc.configureBlocking(Boolean.FALSE);
			sc.register(selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			System.out.println("accept 异常");
			e.printStackTrace();
		}

	}

	private void doRead(SelectionKey key) {
		SocketChannel sc = (SocketChannel) key.channel();
		ByteBuffer reqBuffer = ByteBuffer.allocate(2048);

		try {
			int i = sc.read(reqBuffer);
			if (i >= 0) {
				reqBuffer.flip();
				byte[] bytes = new byte[reqBuffer.remaining()];
				reqBuffer.get(bytes);
				System.out.println(new String(bytes));
				key.attach("res");
				key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
			} else {
				sc.close();
			}
		} catch (IOException e) {
			System.out.println("read 异常");
			try {
				sc.close();
				sc.socket().close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	private void doWrite(SelectionKey key) {
		SocketChannel sc = (SocketChannel) key.channel();
		String handle = (String) key.attachment();// 取出read方法传递的信息。
		ByteBuffer retBuffer = ByteBuffer.wrap(handle.getBytes());

		try {
			sc.write(retBuffer);
			sc.close();
		} catch (IOException e) {
			System.out.println("write 异常");
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println("正在启动服务...");
		new Thread(new NonIOServer(8000)).start();
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值