手写Tomcat:NIO实现方式

 


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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 NIOServer {
	private Selector selector;
	
	public void init() throws IOException {
		//创建一个选择器
		selector = Selector.open();
		//创建一个ServerSocketChanel
		ServerSocketChannel channel = ServerSocketChannel.open();
		//设置非阻塞
		channel.configureBlocking(false);
		//打开一个ServerSocket
		ServerSocket serverSocket = channel.socket();
		//地址
		InetSocketAddress address = new InetSocketAddress(8080);
		//绑定
		serverSocket.bind(address);
		//注册事件
		channel.register(this.selector, SelectionKey.OP_ACCEPT);
	}
	
	public void start() throws IOException {
		while(true) {
			this.selector.select();
			Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
			while(iterator.hasNext()) {
				SelectionKey key = iterator.next();
				iterator.remove();
				if(key.isAcceptable()) {
					//这个请求是客户端的连接请求事件
					accept(key);
				} else if(key.isReadable()) {
					//如果这个请求是读事件
					read(key);
				}
			}
		}
	}
	
	private void accept(SelectionKey key) throws IOException {
		//事件中传过来的,key我们把这个通道拿到
		ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
		SocketChannel channel = serverSocketChannel.accept();
		//把这个设置为非阻塞
		channel.configureBlocking(false);
		//注册读事件
		channel.register(selector, SelectionKey.OP_READ);
	}
	
	private void read(SelectionKey key) throws IOException {
		//创建一个缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		SocketChannel channel = (SocketChannel)key.channel();
		//我们把通道的数据填入缓冲区
		channel.read(buffer);
		String request = new String(buffer.array()).trim();
		System.out.println("客户端的请求内容" + request);
		//把我们的html内容返回给客户端
		
		String outString = "HTTP/1.1 200 OK\n"
				+"Content-Type:text/html; charset=UTF-8\n\n"
				+"<html>\n"
					+"<head>\n"
						+"<title>first page</title>\n"
					+"</head>\n"
					+"<body>\n"
						+"hello fomcat\n"
					+"</body>\n"
				+"</html>";
		
		ByteBuffer outbuffer = ByteBuffer.wrap(outString.getBytes());
		channel.write(outbuffer);
		channel.close();
	}
	
	public static void main(String[] args) {
		NIOServer server = new NIOServer();
		try {
			server.init();
			server.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值