java入门 Netty

一、 参考资料

参考尚硅谷netty教程
https://www.bilibili.com/video/BV1DJ411m7NR?p=7&vd_source=4cd1b6f268e2a29a11bea5d2568836ee

二、 Netty服务端

app.java

package com.sht.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * JAVA Netty
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	
    	NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    	NioEventLoopGroup workGroup = new NioEventLoopGroup();
    	  
    	try {
    		//创建服务器启动对象
        	ServerBootstrap bootStrap =  new ServerBootstrap();
        	
        	bootStrap
        		//设置两个线程组
        		.group(bossGroup, workGroup)
        		.channel(NioServerSocketChannel.class)
        		.option(ChannelOption.SO_BACKLOG, 128)
        		.childOption(ChannelOption.SO_KEEPALIVE, true)
        		.childHandler(new ChannelInitializer<Channel>() {

    				@Override
    				protected void initChannel(Channel ch) throws Exception {
    					// TODO Auto-generated method stub
    					ch.pipeline().addLast(new NettyServerHandler());
    				}
    			});
        	
        	//绑定㐰并且同步
        	ChannelFuture cf = bootStrap.bind(6666).sync();
        	
        	//对关闭通道进行监听
        	cf.channel().closeFuture().sync();
    		
    	}catch (Exception e) {
    		System.out.println("netty exception");
		}finally {
			//优雅关闭
        	bossGroup.shutdownGracefully();
        	workGroup.shutdownGracefully();
		}
    	
    }

}


NettyServerHandler.java

package com.sht.test;

import java.nio.ByteBuffer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends ChannelInboundHandlerAdapter{

	private String reqStr;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//msg转ByteBuffer
		ByteBuf buffer = (ByteBuf) msg;
		reqStr = buffer.toString(CharsetUtil.UTF_8);

		//"收到数据:" + buffer.toString()
		System.out.println(String.format("收到[%s]数据:%s",
				ctx.channel().remoteAddress(),
				reqStr));//CharsetUtil.UTF_8
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//将接收到的数据返回客户端
		ctx.writeAndFlush(Unpooled.copiedBuffer(reqStr,CharsetUtil.UTF_8));
	}
}

三、 Netty客户端

NettyClient.java

package com.sht.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

	public static void main(String[] args) {
		
		NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		
		try
		{
			Bootstrap bootStrap = new Bootstrap();
			
			bootStrap
			//设置两个线程组
			.group(eventLoopGroup)
			.channel(NioSocketChannel.class)					//设置通道实现类
			//.option(ChannelOption.SO_BACKLOG, 128)
			//.childOption(ChannelOption.SO_KEEPALIVE, true)
			.handler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					// TODO Auto-generated method stub
					ch.pipeline().addLast(new NettyClientHandler());
				}
			});
			
			//绑定㐰并且同步
	    	ChannelFuture cf = bootStrap.connect("127.0.0.1",6666).sync();
	    	//对关闭通道进行监听
	    	cf.channel().closeFuture().sync();
		}catch (Exception e) {
			System.out.println("netty exception");
		}finally {
			eventLoopGroup.shutdownGracefully();
		}
	}
}

NettyClientHandler.java

package com.sht.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		String reqStr = "hello";
		ctx.writeAndFlush(Unpooled.copiedBuffer(reqStr,CharsetUtil.UTF_8));
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//msg转ByteBuffer
		ByteBuf buffer = (ByteBuf) msg;
		String respStr = buffer.toString(CharsetUtil.UTF_8);
		
		//"收到数据:" + buffer.toString()
		System.out.println(String.format("收到[%s]数据:%s",
				ctx.channel().remoteAddress(),
				respStr));//CharsetUtil.UTF_8
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		//两种关闭
		//ctx.channel().close();
		ctx.close();
	}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值