JAVA 网络编程(3) SOCKET 非阻塞NIO 处理HTTP请求示例

9 篇文章 0 订阅
6 篇文章 0 订阅

要实现HTTP协议,只需要让TCP协议的回复格式为HTTP的response消息头即可

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.logging.Logger;

public class HttpServer {
	public static void main(String args[]) {
		try (ServerSocketChannel channel = ServerSocketChannel.open();) {
			channel.bind(new InetSocketAddress(9999));
			channel.configureBlocking(false);// 非阻塞
			Selector sel = Selector.open();
			channel.register(sel, SelectionKey.OP_ACCEPT);
			// 创建处理器
			while (true) {
				// 等待请求,每次等待阻塞15s,超过3s后县城继续向下运行,如果传入0或者不传参数则一直阻塞
				if (0 == sel.select(15000)) {
					Logger.getGlobal().info("超时..........");
					continue;
				}
				Logger.getGlobal().info("处理请求...........");
				// 获取处理的SelectionKey
				Iterator<SelectionKey> iter = sel.selectedKeys().iterator();
				while (iter.hasNext()) {
					SelectionKey key = iter.next();
					new Thread(new HttpHandler(key)).run();
					iter.remove();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class HttpHandler implements Runnable{
	private int bufferSize = 1024;
	private String localCharset = "UTF-8";
	private SelectionKey key;
	public HttpHandler(SelectionKey key){
		this.key = key;
	}
	public void handleAccept() throws IOException{
		SocketChannel channel = ((ServerSocketChannel)key.channel()).accept();
		channel.configureBlocking(false);
		channel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
	}
	public void handleRead() throws IOException{
		try (SocketChannel channel = (SocketChannel)key.channel();){
			ByteBuffer buffer = (ByteBuffer)key.attachment();
			buffer.clear();
			if(-1 == channel.read(buffer)){
				channel.close();
			}else{
				buffer.flip();
				String rcvString = Charset.forName(localCharset).newDecoder().decode(buffer).toString();
				String [] requestMsg = rcvString.split("\r\n");
				for (String s : requestMsg) {
					System.out.println(s);
					if(s.isEmpty()){
						break;
					}
				}
				//打印首行信息
				String [] ss = requestMsg[0].split(" ");
				System.out.println();
				System.out.println("Method:\t" + ss[0]);
				System.out.println("url:\t" + ss[1]);
				System.out.println("HTTP Version:\t"+ss[2]);
				System.out.println();
				
				//返回客户端
				StringBuilder sb = new StringBuilder();
				sb.append("HTTP/1.1 200 OK\r\n");
				sb.append("Content-Type:text/html;charset=").append(localCharset).append("\r\n");
				sb.append("\r\n");
				sb.append("<html><head><title>the title报文</title></head>");
				sb.append("<body>");
				sb.append("获得的报文信息为").append("<br/>");
				for (String s : requestMsg) {
					sb.append(s).append("<br/>");
				}
				sb.append("</body>");
				sb.append("</html>");
				buffer = ByteBuffer.wrap(sb.toString().getBytes(localCharset));
				channel.write(buffer);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		try {
			if(key.isAcceptable()){
				handleAccept();
			}
			if(key.isReadable()){
				handleRead();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值