[java] 자바 네티 (Java Netty)를 사용하여 웹 서버를 생성하는 방법은?
네티 (Netty)는 자바 기반의 이벤트 기반 네트워크 애플리케이션 프레임워크로서, 웹 서버를 포함한 다양한 네트워크 애플리케이션을 구축하는 데 사용됩니다. 자바 네티를 사용하여 웹 서버를 생성하는 방법을 아래에 설명드리겠습니다.
- Maven 또는 Gradle과 같은 빌드 도구를 사용하여 프로젝트에 네티 종속성을 추가합니다. 아래는 Maven을 사용하는 경우의 예시입니다.
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.66.Final</version>
</dependency>
- 웹 서버를 생성하기 위해
ServerBootstrap
클래스를 사용합니다. 아래는 간단한 예시입니다.
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class WebServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new WebServerHandler()); // 요청 핸들러 추가
}
});
serverBootstrap.bind(8080).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
ChannelInitializer
인터페이스를 구현하여 요청 처리를 위한 핸들러를 추가합니다.WebServerHandler
는 사용자 정의 요청 핸들러 클래스입니다. 아래는 간단한 예시입니다.
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.CharsetUtil;
public class WebServerHandler extends SimpleChannelInboundHandler<HttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
// 요청 처리 로직 구현
// 예시로서 간단한 "Hello, Netty!" 응답을 반환하도록 구현합니다.
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer("Hello, Netty!", CharsetUtil.UTF_8));
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
ctx.writeAndFlush(response);
}
}
위 예시 코드에서는 네티를 사용하여 간단한 웹 서버를 생성하고, 요청을 처리하기 위한 핸들러를 추가하는 방법을 보여줍니다. 사용자의 요청에 따라 본인의 로직을 구현할 수 있습니다.
자세한 내용은 네티 공식 문서를 참조하시기 바랍니다.