当前位置:   article > 正文

java echo server_netty写Echo Server & Client完整步骤教程(图文)

echoserver java依赖

1.创建Maven工程

e7baa38e0ce1b5e6e3f8461da147b928.png

916dbd8dd2cc4aa65f7cb8ef27c46b65.png

6c9984ad30b9de0e51c942728a5b1dc6.png

dc957a898b0681edb26732743fc135be.png

6ac1343f7bdeb93ed9581f8dcc8c58d7.png

d91a30cb668ef5c76e9addf1e39fabe6.png

c36df44aa17bff53ab3309813be071c0.png

12b35efe896aa91295e6f27ed684a7e9.png

342dd0a48dcd1fa6c1b95437b0130bf4.png

b7ecfbc3811e1e90fe81ce0960e4f98d.png

1.1 父节点的pom.xml代码(root pom文件)

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5 4.0.0

6

7 org.example

8 echo_netty

9 pom

10 1.0-SNAPSHOT

11

12 netty-server

13 netty-client

14

15

16

1.2 子工程netty-server的pom.xml文件代码

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5

6 echo_netty

7 org.example

8 1.0-SNAPSHOT

9

10 4.0.0

11

12 netty-server

13

14

15

1.3 子工程netty-client的pom.xml文件代码

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5

6 echo_netty

7 org.example

8 1.0-SNAPSHOT

9

10 4.0.0

11

12 netty-client

13

14

15

1.4 修改父工程的pom.xml,修改后如下所示:

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5 4.0.0

6

7 org.example

8 echo_netty

9 pom

10 1.0-SNAPSHOT

11

12 netty-server

13 netty-client

14

15

16

17 localhost

18 9999

19

20

21

22

23 io.netty

24 netty-all

25 4.1.10.Final

26 compile

27

28

29

30

31

32

33 maven-compiler-plugin

34

35

36 maven-failsafe-plugin

37

38

39 maven-surefire-plugin

40

41

42 org.codehaus.mojo

43 exec-maven-plugin

44

45

46

47

1.5 修改netty-server的pom.xml,修改后如下所示:

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5

6 echo_netty

7 org.example

8 1.0-SNAPSHOT

9

10 4.0.0

11

12 netty-server

13

14

15

16

17 org.codehaus.mojo

18 exec-maven-plugin

19

20

21 run-server

22

23 java

24

25

26

27

28 com.echo.server.EchoServer

29

30 ${echo-server.port}

31

32

33

34

35

36

37

1.6 修改netty-client的pom.xml,修改后如下所示:

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

5

6 echo_netty

7 org.example

8 1.0-SNAPSHOT

9

10 4.0.0

11

12 netty-client

13

14

15

16

17 org.codehaus.mojo

18 exec-maven-plugin

19

20

21 run-server

22

23 java

24

25

26

27

28 com.echo.client.EchoClient

29

30 ${echo-server.hostname}

31 ${echo-server.port}

32

33

34

35

36

37

38

2. 开始写netty客户端的代码

945d34fa4e215bb12588e3a6fdf9608d.png

0410add28dd7250bc22ba24c9a204593.png

f090cbe25e02a89bfbf1a70bc27f8846.png

f92206e2129225be37f7edde406df665.png

6b1644d74d42c77901fe8096f03fc6d4.png

1cc5b874d5f3ee6ff4165a1486777a66.png

到这里的时候,项目的结构应该是这个样子的,然后让我们修改一下EchoClient.java和EchoClientHandler.java文件的内容,修改后最终代码放在下面,大家请看:

2.1 EchoClient.java的最终代码

1 packagecom.echo.client;2

3 importjava.net.InetSocketAddress;4

5 importcom.echo.client.handler.EchoClientHandler;6 importio.netty.bootstrap.Bootstrap;7 importio.netty.channel.ChannelFuture;8 importio.netty.channel.ChannelInitializer;9 importio.netty.channel.EventLoopGroup;10 importio.netty.channel.nio.NioEventLoopGroup;11 importio.netty.channel.socket.SocketChannel;12 importio.netty.channel.socket.nio.NioSocketChannel;13

14 public classEchoClient {15

16 private finalString host;17 private final intport;18

19 public EchoClient(String host, intport) {20 this.host =host;21 this.port =port;22 }23

24 public static void main(String[] args) throwsException {25 if (args.length != 2) {26 System.err.println(27 "Usage: " + EchoClient.class.getSimpleName() +

28 " ");29 return;30 }31 String host = args[0];32 int port = Integer.parseInt(args[1]);33 newEchoClient(host, port).start();34 }35

36 public void start() throwsException {37 EventLoopGroup group = newNioEventLoopGroup();38 try{39 Bootstrap b = newBootstrap();40 b.group(group)41 .channel(NioSocketChannel.class)42 .remoteAddress(newInetSocketAddress(host, port))43 .handler(new ChannelInitializer() {44

45 @Override46 protected void initChannel(SocketChannel ch) throwsException {47 ch.pipeline().addLast(newEchoClientHandler());48 }49

50 });51 ChannelFuture f =b.connect().sync();52 f.channel().closeFuture().sync();53 } finally{54 group.shutdownGracefully().sync();55 }56 }57

58 }

2.2 EchoClientHandler.java的最终代码

1 packagecom.echo.client.handler;2

3 importio.netty.buffer.ByteBuf;4 importio.netty.buffer.Unpooled;5 importio.netty.channel.ChannelHandler.Sharable;6 importio.netty.channel.ChannelHandlerContext;7 importio.netty.channel.SimpleChannelInboundHandler;8 importio.netty.util.CharsetUtil;9

10 @Sharable11 public class EchoClientHandler extends SimpleChannelInboundHandler{12

13 @Override14 public void channelActive(ChannelHandlerContext ctx) throwsException {15 ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));16 }17

18 @Override19 protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throwsException {20 System.out.println("Client received: " +in.toString(CharsetUtil.UTF_8));21 }22

23 @Override24 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throwsException {25 cause.printStackTrace();26 ctx.close();27 }28

29 }

到这的时候,如果有报错的话,一般是maven没有刷新导致的。

解决方法是,打开父工程的pom.xml ,然后点击idea的右侧的maven刷新按钮,如下图所示

1ce789122300bb4cffa59cd8a76bd95b.png

至此,EchoClient端的代码就写好了。暂时先不启动,先写好EchoServer,再一起启动。下面介绍EchoServer端的代码。

3. 开始写netty服务端的代码

0d3974ef5bffc2652cd3a41b8be27d0b.png

3.2 修改EchoServer.java文件代码,修改后最终代码如下:

1 packagecom.echo.server;2

3 importjava.net.InetSocketAddress;4

5 importcom.echo.server.handler.EchoServerHandler;6 importio.netty.bootstrap.ServerBootstrap;7 importio.netty.channel.ChannelFuture;8 importio.netty.channel.ChannelInitializer;9 importio.netty.channel.EventLoopGroup;10 importio.netty.channel.nio.NioEventLoopGroup;11 importio.netty.channel.socket.SocketChannel;12 importio.netty.channel.socket.nio.NioServerSocketChannel;13

14 public classEchoServer {15

16 private final intport;17

18 public EchoServer(intport) {19 this.port =port;20 }21

22 public void start() throwsException {23 final EchoServerHandler serverHandler = newEchoServerHandler();24 EventLoopGroup group = newNioEventLoopGroup();25 try{26 ServerBootstrap b = newServerBootstrap();27 b.group(group)28 .channel(NioServerSocketChannel.class)29 .localAddress(newInetSocketAddress(port))30 .childHandler(new ChannelInitializer() {31

32 @Override33 protected void initChannel(SocketChannel ch) throwsException {34 ch.pipeline().addLast(serverHandler);35 }36 });37 //此处绑定服务器,并等待绑定完成。对sync()方法的调用将导致当前Thread阻塞,直到绑定完成

38 ChannelFuture f =b.bind().sync();39 //由于调用了sync()方法,程序将会阻塞等待,直到服务器的Channel关闭

40 f.channel().closeFuture().sync();41 } finally{42 group.shutdownGracefully().sync();43 }44 }45

46 public static void main(String[] args) throwsException {47 if (args.length != 1) {48 System.err.println(49 "Usage: " + EchoServer.class.getSimpleName() + " "

50 );51 return;52 }53 int port = Integer.parseInt(args[0]);54 newEchoServer(port).start();55 }56

57 }

3.3 修改EchoServerHandler.java文件代码,修改后最终代码如下:

1 packagecom.echo.server.handler;2

3 importio.netty.buffer.ByteBuf;4 importio.netty.buffer.Unpooled;5 importio.netty.channel.ChannelHandler.Sharable;6 importio.netty.channel.ChannelFutureListener;7 importio.netty.channel.ChannelHandlerContext;8 importio.netty.channel.ChannelInboundHandlerAdapter;9 importio.netty.util.CharsetUtil;10

11 //@Sharable标示一个ChannelHandler可以被多个Channel安全共享

12 @Sharable13 public class EchoServerHandler extendsChannelInboundHandlerAdapter {14

15 @Override16 public void channelRead(ChannelHandlerContext ctx, Object msg) throwsException {17 ByteBuf in =(ByteBuf) msg;18 System.out.println(19 "Server received: " +in.toString(CharsetUtil.UTF_8));20 //将接收到的消息写给发送者,即客户端,而不冲刷出站消息

21 ctx.write(in);22 }23

24 @Override25 public void channelReadComplete(ChannelHandlerContext ctx) throwsException {26 //将未决消息冲刷到远程节点,并且关闭该Channel

27 ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)28 .addListener(ChannelFutureListener.CLOSE);29 }30

31 @Override32 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throwsException {33 cause.printStackTrace();34 ctx.close();35 }36

37 }

至此,所有的代码已经写好,下一步进行运行测试

4.运行代码

4.1 打包代码

422be768cf94cdd2af76159340044997.png

790e676c8bc250a02edffb63cc17f0ac.png

当出现BUILD SUCCESS的时候,代表代码已经打包好了。

4.2 运行server端

ef8b52d2f4e3bc030ab4b7a4e69304bf.png

84a70afe18bed5bc696b37c404f68b92.png

出现一直在转圈的时候,代表server端启动成功了

4.3 运行client端

ca0d1a4cc0bbb7b9c313e75e06bf6c1e.png

双击运行client端,然后稍等片刻,会发现下图已经出现了

Client received: Netty rocks!

这一行字。说明客户端和服务端通信成功。

c3069fa3e02f8f215d461e0f9cb420ba.png

接着看一下server端打印的输出,如下图:

44c9901ab4a4182c0c8e6a5bdcb03da1.png

可以看到,server端已经输出了从客户端收到的消息!!!

至此,所有的演示都结束了,大家自己动手进行实践吧。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/160760
推荐阅读
相关标签
  

闽ICP备14008679号