好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

从入门到超神进阶的Netty群聊系统

服务端

服务端一样的需要创建bossgroup 和 workgroup , 然后使用serverbootstrap 来配置netty和启动netty。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

public class nettygroupchatserver {

     public static void main(string[] args) {

         new nettygroupchatserver().start();

     }

     //监听

    public void start(){

         //循环组

        nioeventloopgroup bossgroup = new nioeventloopgroup();

        nioeventloopgroup workgroup = new nioeventloopgroup();

        //启动引导

        serverbootstrap bootstrap = new serverbootstrap();

        //netty配置

        bootstrap.group(bossgroup,workgroup)

                .option(channeloption.so_backlog, 32 )

                .childoption(channeloption.so_keepalive, true )

                .channel(nioserversocketchannel. class )

                .childhandler( new channelinitializer<socketchannel>() {

                    @override

                    protected void initchannel(socketchannel channel) throws exception {

                        //解码器

                        channel.pipeline().addlast( "decoder" , new stringdecoder());

                        //编码器

                        channel.pipeline().addlast( "encoder" , new stringencoder());

                        //处理器

                        channel.pipeline().addlast( "nettygroupchathandler" , new nettygroupchatserverhandler());

                    }

                });

        try {

            //启动服务

            channelfuture future = bootstrap.bind( new inetsocketaddress( "127.0.0.1" , 8888 )).sync();

            future.channel().closefuture().sync();

        } catch (interruptedexception e) {

            e.printstacktrace();

        } finally {

            //关闭资源

            bossgroup.shutdowngracefully();

            workgroup.shutdowngracefully();

        }

    }

}

服务端处理器我们通过继承 simplechannelinboundhandler 入站handler来处理消息。

其中提供了几个方法

channelread0 ():读取消息 handlerremoved ():客户端断开 handleradded ():客户端建立连接 exceptioncaught ():出现异常

具体代码如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

public class nettygroupchatserverhandler extends simplechannelinboundhandler<string> {

     //把所有客户端的channel保存起来

     private static channelgroup channels = new defaultchannelgroup(globaleventexecutor.instance);

     private static simpledateformat dateformat = new simpledateformat( "yyyy-mm-dd hh:mm:ss" );

     @override

     protected void channelread0(channelhandlercontext ctx, string msg) throws exception {

         string message = dateformat.format( new date())+ ":%s:" +msg;

         //消息转发给所有的客户端

         channels.foreach(channel -> {

             if (channel == ctx.channel()){

                 string sendmsg = string.format(message, "我" );

                 channel.writeandflush(sendmsg);

                 system.out.println(sendmsg);

 

             } else {

                 string sendmsg = string.format(message, ctx.channel().remoteaddress());

                 channel.writeandflush(sendmsg);

                 system.out.println(sendmsg);

             }

         });

     }

     //断开连接 , 把消息广播给其他客户端

     @override

     public void handlerremoved(channelhandlercontext ctx) throws exception {

         string message = dateformat.format( new date())+ ":" +ctx.channel().remoteaddress()+ ":断开连接" ;

         channels.writeandflush(message);

         system.out.println(message);

     }

     //建立连接

     @override

     public void handleradded(channelhandlercontext ctx) throws exception {

         string message = dateformat.format( new date())+ ":" +ctx.channel().remoteaddress()+ ":加入聊天室" ;

         //自动把消息广播给其客户端

         channels.writeandflush(message);

         //客户端加入组

         channels.add(ctx.channel());

         system.out.println(message);

     }

     //出现异常

     @override

     public void exceptioncaught(channelhandlercontext ctx, throwable cause) throws exception {

         ctx.channel().close();

     }

     //客户端退出

     @override

     public void channelinactive(channelhandlercontext ctx) throws exception {

         string message = dateformat.format( new date())+ ":" +ctx.channel().remoteaddress()+ ":退出聊天室" ;

         system.out.println(message);

     }

     //客户端出于活动

     @override

     public void channelactive(channelhandlercontext ctx) throws exception {

         string message = dateformat.format( new date())+ ":" +ctx.channel().remoteaddress()+ ":上线啦" ;

         system.out.println(message);

     }

}

客户端

客户端需要创建一个循环事件组,然后通过bootstrap去启动,然后扫描键盘输入作为数据源来把信息发送给服务端

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

public class nettygroupchatclient {

     public static void main(string[] args) {

         new nettygroupchatclient().start();

     }

     public void start(){

         nioeventloopgroup eventloopgroup = new nioeventloopgroup();

         bootstrap bootstrap = new bootstrap();

         bootstrap.group(eventloopgroup)

                 .channel(niosocketchannel. class )

                 .handler( new channelinitializer<socketchannel>() {

                     @override

                     protected void initchannel(socketchannel channel) throws exception {

                         //解码器

                         channel.pipeline().addlast( "decoder" , new stringdecoder());

                         //编码器

                         channel.pipeline().addlast( "encoder" , new stringencoder());

                         //处理器

                         channel.pipeline().addlast( "nettygroupchatclienthandler" , new nettygroupchatclienthandler());

                     }

                 });

         try {

             channelfuture future = bootstrap.connect( new inetsocketaddress( "127.0.0.1" , 8888 )).sync();

             //通道

             channel channel = future.channel();

             //扫描键盘输入

             scanner scanner = new scanner(system.in);

             while (scanner.hasnextline()){

                 string message = scanner.nextline();

                 //发送数据

                 channel.writeandflush(message);

             }

         } catch (interruptedexception e) {

         } finally {

             eventloopgroup.shutdowngracefully();

         }

     }

}

对于处理器只需要接收服务端转发过来的消息即可

?

1

2

3

4

5

6

public class nettygroupchatclienthandler extends simplechannelinboundhandler<string> {

     @override

     protected void channelread0(channelhandlercontext ctx, string msg) throws exception {

         system.out.println(msg);

     }

}

启动服务端和多个客户端,效果如下



到此这篇关于从入门到超神系列的netty群聊系统的文章就介绍到这了,更多相关netty群聊系统内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/u014494148/article/details/119721394

查看更多关于从入门到超神进阶的Netty群聊系统的详细内容...

  阅读:12次