netty实现聊天室

雨点打透心脏的1/2处 2022-01-20 03:21 447阅读 0赞

什么是IO多路复用:
I/O多路复用,I/O是指网络I/O, 多路指多个TCP连接(即socket或者channel),复用指复用一个或几个线程。
简单来说:就是使用一个或者几个线程处理多个TCP连接
最大优势是减少系统开销小,不必创建过多的进程/线程,也不必维护这些进程/线程

epoll:

1)没fd这个限制,所支持的FD上限是操作系统的最大文件句柄数,1G内存大概支持10万个句柄
2)效率提高,使用回调通知而不是轮询的方式,不会随着FD数目的增加效率下降

3)通过callback机制通知,内核和用户空间mmap同一块内存实现

依赖:

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.36.Final</version>
  5. </dependency>

1、服务端

  1. package com.example.demo.chat;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  11. import io.netty.handler.codec.Delimiters;
  12. import io.netty.handler.codec.string.StringDecoder;
  13. import io.netty.handler.codec.string.StringEncoder;
  14. import io.netty.util.CharsetUtil;
  15. public class ChatServer {
  16. private int port = 8080;
  17. public static void main(String[] args) throws Exception {
  18. new ChatServer().start();
  19. }
  20. private void start() throws Exception {
  21. EventLoopGroup bossGroup = new NioEventLoopGroup();
  22. EventLoopGroup workGroup = new NioEventLoopGroup();
  23. try {
  24. ServerBootstrap bootstrap = new ServerBootstrap();
  25. bootstrap.group(bossGroup, workGroup)//
  26. .channel(NioServerSocketChannel.class)//
  27. .childHandler(new ChannelInitializer<SocketChannel>() {
  28. @Override
  29. protected void initChannel(SocketChannel ch) throws Exception {
  30. ch.pipeline()//
  31. .addLast("framer", new DelimiterBasedFrameDecoder(2048, Delimiters.lineDelimiter()))//
  32. .addLast("decoder", new StringDecoder(CharsetUtil.UTF_8))//
  33. .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))//
  34. .addLast("handler", new ChatServerHandler());
  35. }
  36. })//
  37. .option(ChannelOption.SO_BACKLOG, 1024)//
  38. .childOption(ChannelOption.SO_KEEPALIVE, true);
  39. ChannelFuture future = bootstrap.bind(port).sync();
  40. System.out.println("=======================服务端启动了========================");
  41. future.channel().closeFuture().sync();
  42. } finally {
  43. bossGroup.shutdownGracefully();
  44. workGroup.shutdownGracefully();
  45. }
  46. }
  47. }

2、服务端处理器

  1. package com.example.demo.chat;
  2. import io.netty.channel.Channel;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.SimpleChannelInboundHandler;
  5. import io.netty.channel.group.ChannelGroup;
  6. import io.netty.channel.group.DefaultChannelGroup;
  7. import io.netty.util.concurrent.GlobalEventExecutor;
  8. public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
  9. // 全局频道变量,存储所有客户端
  10. private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
  11. @Override
  12. public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  13. for (Channel channel : channels) {
  14. channel.writeAndFlush(ctx.channel().remoteAddress() + ",进来啦\n");
  15. }
  16. channels.add(ctx.channel());
  17. }
  18. @Override
  19. public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  20. channels.remove(ctx.channel());
  21. for (Channel channel : channels) {
  22. channel.writeAndFlush(ctx.channel().remoteAddress() + ",离开啦\n");
  23. }
  24. }
  25. @Override
  26. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  27. System.out.println(ctx.channel().remoteAddress() + ",上线了\n");
  28. }
  29. @Override
  30. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  31. System.out.println(ctx.channel().remoteAddress() + ",离线了\n");
  32. }
  33. @Override
  34. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  35. cause.printStackTrace();
  36. }
  37. @Override
  38. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  39. Channel ch = ctx.channel();
  40. for (Channel channel : channels) {
  41. if (ch == channel) {
  42. channel.writeAndFlush("我说:" + msg + "\n");
  43. } else {
  44. channel.writeAndFlush(channel.remoteAddress() + " 说:" + msg + "\n");
  45. }
  46. }
  47. }
  48. }

3、客户端

  1. package com.example.demo.chat;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import io.netty.bootstrap.Bootstrap;
  5. import io.netty.channel.ChannelFuture;
  6. import io.netty.channel.ChannelInitializer;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  12. import io.netty.handler.codec.Delimiters;
  13. import io.netty.handler.codec.string.StringDecoder;
  14. import io.netty.handler.codec.string.StringEncoder;
  15. import io.netty.util.CharsetUtil;
  16. public class ChatClient {
  17. private int port = 8080;
  18. private String host = "127.0.0.1";
  19. public static void main(String[] args) throws Exception {
  20. new ChatClient().start();
  21. }
  22. private void start() throws Exception {
  23. EventLoopGroup group = new NioEventLoopGroup();
  24. try {
  25. Bootstrap bootstrap = new Bootstrap();
  26. bootstrap.group(group)//
  27. .channel(NioSocketChannel.class)//
  28. .handler(new ChannelInitializer<SocketChannel>() {
  29. @Override
  30. protected void initChannel(SocketChannel ch) throws Exception {
  31. ch.pipeline()//
  32. .addLast("framer", new DelimiterBasedFrameDecoder(2048, Delimiters.lineDelimiter()))//
  33. .addLast("decoder", new StringDecoder(CharsetUtil.UTF_8))//
  34. .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))//
  35. .addLast("handler", new ChatClientHandler());
  36. }
  37. });
  38. ChannelFuture future = bootstrap.connect(host, port).sync();
  39. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  40. while (true) {
  41. future.channel().writeAndFlush(reader.readLine() + "\n");
  42. }
  43. } finally {
  44. group.shutdownGracefully();
  45. }
  46. }
  47. }

4、客户端处理器

  1. package com.example.demo.chat;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.SimpleChannelInboundHandler;
  4. public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
  5. @Override
  6. protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
  7. System.out.println(msg);
  8. }
  9. }

发表评论

表情:
评论列表 (有 0 条评论,447人围观)

还没有评论,来说两句吧...

相关阅读