[java] 자바 네티 (Java Netty)를 사용하여 웹소켓 채팅 서버를 만드는 방법은?

웹소켓은 실시간 양방향 통신을 지원하는 프로토콜로, 자바 Netty를 사용하여 웹소켓 채팅 서버를 만들 수 있습니다. 이번 블로그에서는 Netty를 이용하여 간단한 웹소켓 채팅 서버를 구현하는 방법에 대해 알아보겠습니다.

1. Maven 프로젝트 설정

먼저 Maven을 사용하여 프로젝트를 설정합니다. pom.xml 파일에 다음 의존성을 추가합니다.

<dependencies>
  <dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.65.Final</version>
  </dependency>
</dependencies>

2. 웹소켓 채널핸들러 구현하기

Netty를 사용하여 웹소켓 채팅 서버를 만들기 위해 SimpleChannelInboundHandler 클래스를 상속받는 WebSocketServerHandler 클래스를 구현합니다.

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
    String message = frame.text(); // 클라이언트로부터 받은 메시지

    // 메시지 처리 로직 구현
    System.out.println("Received message: " + message);

    // 클라이언트에게 메시지 전송
    ctx.channel().writeAndFlush(new TextWebSocketFrame("Server echo: " + message));
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}

3. 웹소켓 서버 구현하기

웹소켓 채널핸들러를 등록하고 웹소켓 서버를 구현하기 위해 WebSocketServerInitializer 클래스를 작성합니다.

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

  @Override
  protected void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline()
      .addLast(new HttpServerCodec()) // HTTP 요청과 응답을 처리하기 위한 코덱
      .addLast(new WebSocketServerProtocolHandler("/ws")) // 웹소켓 프로토콜 처리를 위한 핸들러
      .addLast(new WebSocketServerHandler()); // 사용자 정의 웹소켓 채널핸들러
  }
}

4. 웹소켓 서버 실행

웹소켓 서버를 실행하기 위해 WebSocketServer 클래스를 작성합니다.

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WebSocketServer {

  public static void main(String[] args) throws InterruptedException {
    // 이벤트 루프 그룹 생성
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap serverBootstrap = new ServerBootstrap();
      serverBootstrap.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class) // NIO 사용
          .childHandler(new WebSocketServerInitializer()); // 웹소켓 서버 설정

      ChannelFuture channelFuture = serverBootstrap.bind(8080).sync(); // 서버 포트 설정

      channelFuture.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
}

5. 실행 결과 확인하기

웹소켓 채팅 서버를 실행하고, 클라이언트로부터 메시지를 전송하면 서버는 받은 메시지를 출력하고, 클라이언트에게 메시지를 다시 전송합니다.

이제 자바 Netty를 사용하여 간단한 웹소켓 채팅 서버를 구현하는 방법을 알아보았습니다. 이 예제를 기반으로 더 발전된 웹소켓 채팅 서버를 구현해보세요!

참고 자료