Nettyを使って実現した簡単なHTTPサーバです。
Nettyを使って実現した簡単なHTTPサーバです。
1.HttpServer,Httpサービス開始クラスは、各種スレッドとチャンネルを初期化するために使用されます。
2.Http ChanelInitService、チャネル初期化類
1.HttpServer,Httpサービス開始クラスは、各種スレッドとチャンネルを初期化するために使用されます。
public class HttpServer { public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new HttpChannelInitService()).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception { int port = 8080; if (args != null && args.length > 0) { try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
}
} new HttpServer().bind(port);
}
}
2.Http ChanelInitService、チャネル初期化類
public class HttpChannelInitService extends ChannelInitializer<SocketChannel>{
@Override protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new HttpResponseEncoder());
sc.pipeline().addLast(new HttpRequestDecoder());
sc.pipeline().addLast(new HttpChannelHandler());
}
}
3.Http ChanelHandler、処理要求のHTTP情報public class HttpChannelHandler extends ChannelInboundHandlerAdapter { private HttpRequest request = null; private FullHttpResponse response = null;
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) {
request = (HttpRequest) msg;
String uri = request.getUri();
String res = ""; try {
res = ReadUtils.readFile(uri.substring(1));
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
setJsessionId(isHasJsessionId());
setHeaders(response);
} catch (Exception e) {// , res = "<html><body>Server Error</body></html>";
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
setHeaders(response);
} if(response!=null)
ctx.write(response);
} if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf buf = content.content();
System.out.println(buf.toString(CharsetUtil.UTF_8));
buf.release();
}
} /** * HTTP */ private void setHeaders(FullHttpResponse response) {
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.headers().set(HttpHeaders.Names.CONTENT_LANGUAGE, response.content().readableBytes()); if (HttpHeaders.isKeepAlive(request)) {
response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
}
} /** * JSESSIONID */ private void setJsessionId(boolean isHasJsessionId) { if(!isHasJsessionId){
CookieEncoder encoder = new CookieEncoder(true);
encoder.addCookie(HttpSession.SESSIONID, HttpSessionManager.getSessionId());
String encodedCookie = encoder.encode();
response.headers().set(HttpHeaders.Names.SET_COOKIE, encodedCookie);
}
} /** * cookie JSESSIONID
* JSESSIONID
* @author yangsong
* @date 2015 3 26 2:08:07 */ private boolean isHasJsessionId() { try {
String cookieStr = request.headers().get("Cookie");
Set<Cookie> cookies = CookieDecoder.decode(cookieStr);
Iterator<Cookie> it = cookies.iterator(); while(it.hasNext()){
Cookie cookie = it.next(); if(cookie.getName().equals(HttpSession.SESSIONID)){ if(HttpSessionManager.isHasJsessionId(cookie.getValue())){ return true;
}
System.out.println("JSESSIONID:"+cookie.getValue());
}
}
} catch (Exception e1) {
e1.printStackTrace();
} return false;
}
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("server channelReadComplete..");
ctx.flush();// SocketChannel }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("server exceptionCaught..");
ctx.close();
}
}
5.HttpSession Manager、Session管理類/** * HttpSession */ public class HttpSessionManager { private static final HashMap<String,HttpSession> sessionMap = new HashMap<String, HttpSession>(); /** * session sessionId */ public static String getSessionId(){ synchronized (sessionMap) {
HttpSession httpSession = new HttpSession();
sessionMap.put(httpSession.getSessionID(), httpSession); return httpSession.getSessionID();
}
} /** * session */ public static boolean isHasJsessionId(String sessiondId){ synchronized (sessionMap) { return sessionMap.containsKey(sessiondId);
}
}
}
6.ページ情報とクッキー