NETTY使用
Netty Server端
导入Netty的库包
找到工程中的pom.xml文件,在dependencies中添加如下代码
1 2 3 4 5
| <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.48.Final</version> </dependency>
|
创建NettyServer
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 57 58 59 60 61 62 63 64
| import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; 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;
public class NettyServer { private int port;
public NettyServer(int port) { this.port = port; bind(); }
private void bind() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup();
try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p = socketChannel.pipeline(); p.addLast(new NettyServerHandler()); } }); ChannelFuture channelFuture = bootstrap.bind(port).sync(); if (channelFuture.isSuccess()) { System.err.println("启动Netty服务成功,端口号:" + this.port); } channelFuture.channel().closeFuture().sync();
} catch (Exception e) { System.err.println("启动Netty服务异常,异常信息:" + e.getMessage()); e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } }
public static void main(String[] args) throws InterruptedException { new NettyServer(10086); } }
|
创建NettyServerHandler
新建NettyServerHandler类,用来实现Server端接收和处理消息的逻辑
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.io.UnsupportedEncodingException;
@ChannelHandler.Sharable public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf); System.err.println("服务器接收到客户端消息:" + recieved);
try { ctx.writeAndFlush(getSendByteBuf("你好,客户端")); System.err.println("服务器回复消息:你好,客户端"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("一台客户端已经连接"); }
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("一个客户端的关闭了连接"); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("发生了一个异常:" + cause.getMessage()); }
private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException { byte[] req = message.getBytes("UTF-8"); ByteBuf pingMessage = Unpooled.buffer(); pingMessage.writeBytes(req); return pingMessage; } }
|
启动Server端
启动后打印信息
Netty Client端
导入Netty的库包
导入代码同上面的Server端代码
创建NettyClient
新建NettyClient类
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 57
| public class NettyClient {
private int port;
private String host;
public NettyClient(int port, String host) throws InterruptedException { this.port = port; this.host = host; start(); }
private void start() throws InterruptedException { EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(eventLoopGroup); bootstrap.remoteAddress(host, port); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); if (channelFuture.isSuccess()) { System.err.println("连接服务器成功"); } channelFuture.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } }
public static void main(String[] args) throws InterruptedException { new NettyClient(10086, "localhost"); } }
|
创建NettyClientHandler
新建NettyClientHandler类,用来实现Server端接收和处理消息的逻辑
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
| import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.UnsupportedEncodingException;
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { byte[] data = "你好,服务器".getBytes(); ByteBuf firstMessage = Unpooled.buffer(); firstMessage.writeBytes(data); ctx.writeAndFlush(firstMessage); System.err.println("客户端发送消息:你好,服务器"); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String rev = getMessage(buf); System.err.println("客户端收到服务器消息:" + rev); }
private String getMessage(ByteBuf buf) { byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }
|
启动Client端
客户端输出
1 2 3
| 连接服务器成功 客户端发送消息:你好,服务器 客户端收到服务器消息:你好,客户端
|
服务端输出
1 2 3 4
| 启动Netty服务成功,端口号:10086 一台客户端已经连接 服务器接收到客户端消息:你好,服务器 服务器回复消息:你好,客户端
|