Java HTTP 프로 토 콜 구현

20943 단어 Java
Java HTTP 프로 토 콜 구현
코드:
package com.we;

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.nio.charset.Charset;
import java.util.Iterator;

public class HttpServer {
	public static void main(String[] args) throws IOException {
		
		 //    ServerSocketChanne1,  8080  
		 ServerSocketChannel ssc = ServerSocketChannel.open(); 
		 ssc.socket().bind(new InetSocketAddress(8080));
		 //         
		 ssc.configureBlocking(false);
		 //  ssc     
		 Selector selector = Selector.open();
		 ssc.register(selector, SelectionKey.OP_ACCEPT);
		 //      
		 while (true) {
			//     ,      3s,  3s         ,    0          
			if (selector.select(3000) == 0) {
				continue;
			}
		    //        SelectionKey
			Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
			
			while (keyIter.hasNext()) {
				SelectionKey key  = keyIter.next();
				//        SelectionKey
				new Thread(new HttpHandler(key)).run();
				//     ,      SelectionKey            key
				keyIter.remove();
			}
		 } 
	}
	
	private static class HttpHandler implements Runnable {
		private int bufferSize = 1024;
		private String localCharest = "UTF-8";
		private SelectionKey key;
		
		public HttpHandler(SelectionKey key) {
			this.key = key;
		}
		
		public void handleAccept() throws IOException {
			SocketChannel clientChannel = ((ServerSocketChannel)key.channel()).accept();
			clientChannel.configureBlocking(false);
			clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
		}
		
		public void handleRead() throws IOException {
			//   channel
			SocketChannel sc = (SocketChannel)key.channel();
			//   buffer   
			ByteBuffer buffer = (ByteBuffer)key.attachment();
			buffer.clear();
			//          
			if (sc.read(buffer) == -1) {
				sc.close();
			} else {
				//       
				buffer.flip();
				String  receivedString = Charset.forName(localCharest).newDecoder().decode(buffer).toString();
			    //           
				String[] requestMessage = receivedString.split("\r
"
); for (String s : requestMessage) { System.out.println(s); // if (s.isEmpty()) { break; } } // String[] firstLine = requestMessage[0].split(" "); System.out.println(); System.out.println("Method:\t" + firstLine[0]); System.out.println("url:\t" + firstLine[1]); System.out.println("HTTP Version:\t" + firstLine[2]); System.out.println(); // StringBuilder sendString = new StringBuilder(); sendString.append("HTTP/1.1 200 OK\r
"
);// ,200 sendString.append("Content-Type:text/html;charset=" + localCharest + "\r
"
); sendString.append("\r
"
);// sendString.append(" "); sendString.append(" :
"
); for (String s : requestMessage) { sendString.append(s + "
"
); } sendString.append("

좋은 웹페이지 즐겨찾기