Netty入门实例-02

一、需求 

建立netty通讯并通过编写客户端的方式发送消息和响应消息。

二、环境

idea 2018

JDK1.8

maven 3.3.1

Netty 5.0.0.Alpha2

三、代码实现

1、实现server端的ServerHandler

创建一个ServerHandler 继承 Netty的ChannelInboundHandlerAdapter 类。并重写方法 [idea快捷键 Ctrl+o]


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.util.CharsetUtil;
 
@Sharable			//表明一个ChannelHandler可以被多个Channel安全的共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//每次收到消息时被调用
		ByteBuf in = (ByteBuf) msg;
		System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));		//把消息打印到控制台
		ctx.write(in);				//将收到的消息写入发送方,不刷新输出消息
	}
	
	@Override						//用来通知handler上一个ChannelRead()是被这批消息中的最后一个消息调用
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//刷新挂起的数据到远端,然后关闭Channel
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}
	
	@Override						//在读操作异常被抛出时被调用
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();			//打印异常堆栈跟踪消息
		ctx.close();						//关闭这个Channel
	}
}

2、实现服务端server


import com.ygq.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;
 
/**
 * 服务端

 */
public class EchoServer {
	private final int port;

	public EchoServer(int port) {
		this.port = port;
	}

	public void start() throws Exception {
		final EchoServerHandler serverHandler = new EchoServerHandler();
		EventLoopGroup group = new NioEventLoopGroup();    //创建EventLoopGroup
		try {
			ServerBootstrap b = new ServerBootstrap();    //创建ServerBootstrap
			b.group(group)
					.channel(NioServerSocketChannel.class)        //指定使用一个NIO传输Channel
					.localAddress(new InetSocketAddress(port))    //用指定的端口设置socket地址
					.childHandler(new ChannelInitializer<SocketChannel>() {    //在Channel的ChannelPipeline中加入EchoServerHandler
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(serverHandler);//EchoServerHandler是@Sharable的,所以我们可以一直用同一个实例
						}
					});
			ChannelFuture f = b.bind().sync();//异步的绑定服务器,sync()一直等到绑定完成
			f.channel().closeFuture().sync();//获得这个Channel的CloseFuture,阻塞当前线程直到关闭操作完成
		} finally {
			group.shutdownGracefully().sync();//关闭EventLoopGroup,释放所有资源
		}

	}

	public static void main(String args[]) throws Exception {
		new EchoServer(8080).start();
	}

}

3、实现client端的Handler


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;


@Sharable						//标记这个类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
	
	@Override							//和服务器的连接建立起来后被调用
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//当收到连接成功的通知,发送一条消息
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
	}
 
//	@Override							//从服务器收到一条消息时被调用
//	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//		System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8));//打印收到的消息到日志
//	}
	
	@Override							//处理过程中异常发生时被调用
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();//异常发生时,记录错误日志,关闭Channel
		ctx.close();
	}

	protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
		System.out.println("收到的消息了....."+byteBuf.toString(CharsetUtil.UTF_8));
	}
}

四、实现client端

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;


@Sharable						//标记这个类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
	
	@Override							//和服务器的连接建立起来后被调用
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//当收到连接成功的通知,发送一条消息
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
	}
 
	
	@Override							//处理过程中异常发生时被调用
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();//异常发生时,记录错误日志,关闭Channel
		ctx.close();
	}

	protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
		System.out.println("收到的消息了....."+byteBuf.toString(CharsetUtil.UTF_8));
	}
}

五、开启服务端并发送消息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

再写一行代码就下班

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值