๐Ÿ“• CS ์Šคํ„ฐ๋””/๋„คํŠธ์›Œํฌ

๋”ฐ๋ผํ•˜๋ฉด ๋˜๋Š” Netty ๊ธฐ๋ฐ˜ ๊ฐ„๋‹จํ•œ Live Chat ์„œ๋ฒ„ ์˜ˆ์ œ

iknowDev 2023. 1. 19. 15:05
๐Ÿ’ก ๋น„๋™๊ธฐ ์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ ๋„คํŠธ์›Œํฌ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํ”„๋ ˆ์ž„์›Œํฌ์ธ Netty๋ฅผ ํ•™์Šตํ•˜๋ฉฐ Simple Chat Server๋ฅผ ๊ตฌ์ถ•ํ•  ์ˆ˜ ์žˆ๋‹ค.

์ง€๋‚œ๋ฒˆ ๋งŒ๋“ค์—ˆ๋˜ EchoServer๋ฅผ ์‹ฌํ™”ํ•ด Live Chat ์„œ๋ฒ„๋ฅผ ๊ตฌํ˜„ํ•ด๋ณด์ž

์ €๋ฒˆ ์˜ˆ์ œ๋Š” EchoServer.java์™€ EchoServerHandler.java ํŒŒ์ผ๋กœ ๊ตฌ์„ฑ๋˜์—ˆ์ง€๋งŒ,

์ด๋ฒˆ ์˜ˆ์ œ์˜ ํŒŒ์ผ ๊ตฌ์„ฑ์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

- ChatServer.java

- ChatServerHandler.java

- ChatClient.java

- ChatClientHandler.java

 

ChatServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public final class ChatServer {
	static final int PORT = 8007;

	public static void main(String[] args) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup) // Set boss & worker groups
					.channel(NioServerSocketChannel.class)// Use NIO to accept new connections.
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();
                            
							p.addLast(new StringDecoder());
							p.addLast(new StringEncoder());

							// This is our custom server handler which will have logic for chat.
							p.addLast(new ChatServerHandler());
						}
					});

			// Start the server.
			ChannelFuture f = b.bind(PORT).sync();
			System.out.println("Chat Server started. Ready to accept chat clients.");

			// Wait until the server socket is closed.
			f.channel().closeFuture().sync();
		} finally {
			// Shut down all event loops to terminate all threads.
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}

 

ChatServerHandler.java

import java.util.ArrayList;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
	static final List<Channel> channels = new ArrayList<Channel>();

	@Override
	public void channelActive(final ChannelHandlerContext ctx) {
		System.out.println("Client joined - " + ctx);
		channels.add(ctx.channel());
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println("Server received - " + msg);
		for (Channel c : channels) {
			c.writeAndFlush("-> " + msg + '\n');
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println("Closing connection for client - " + ctx);
		ctx.close();
	}
}

 

ChatClient.java

import java.util.Scanner;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatClient {
	static final String HOST = "127.0.0.1";
	static final int PORT = 8007;
	static String clientName;

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter your name: ");
		if (scanner.hasNext()) {
			clientName = scanner.nextLine();
			System.out.println("Welcome " + clientName);
		}

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group) // Set EventLoopGroup to handle all eventsf for client.
					.channel(NioSocketChannel.class)// Use NIO to accept new connections.
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();
                            
							p.addLast(new StringDecoder());
							p.addLast(new StringEncoder());

							// This is our custom client handler which will have logic for chat.
							p.addLast(new ChatClientHandler());

						}
					});

			// Start the client.
			ChannelFuture f = b.connect(HOST, PORT).sync();

			while (scanner.hasNext()) {
				String input = scanner.nextLine();
				Channel channel = f.sync().channel();
				channel.writeAndFlush("[" + clientName + "]: " + input);
				channel.flush();
			}

			// Wait until the connection is closed.
			f.channel().closeFuture().sync();
		} finally {
			// Shut down the event loop to terminate all threads.
			group.shutdownGracefully();
		}
	}
}

 

ChatClientHandler.java

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println("Message: " + msg);
	}
}

1. ChatServer.java๋ฅผ Runํ•œ๋‹ค.

ChatServer Console

2. ChatClient.java๋ฅผ Runํ•œ๋‹ค.

3. ์ด๋ฆ„์„ ์ž…๋ ฅํ•œ๋‹ค.

ChatClient 1 Console
ChatServer Console

4. iknowDev๊ฐ€ hello world๋ผ๊ณ  ์ž…๋ ฅํ–ˆ๋‹ค.

ChatClient 1 Console
ChatServer Console

 5. ClientServer๋ฅผ ํ•˜๋‚˜ ๋” Runํ•˜๊ณ  ์—ฌ๋Ÿฌ ์‚ฌ์šฉ์ž์˜ ๋น„๋™๊ธฐ ๋Œ€ํ™”๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

ChatClient 2 Console
ChatClient 1 Console
ChatServer Console

 

 

Netty Project | Understanding Netty using simple real-world example of Chat server client | Good for beginners - Its All Binary

In this article we will understand Netty in simplistic way with real world example of Chat server client example. What…

itsallbinary.com