Netty之HelloWorld

Server:

package lqt.netty.helloworld;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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 Server {

	public static void main(String[] args) throws Exception {
		EventLoopGroup pGroup=new NioEventLoopGroup();					//1 一个是用于处理服务器端接收客户端连接的
		EventLoopGroup cGroup=new NioEventLoopGroup();					//一个是进行网络通信的(网络读写的)
		ServerBootstrap b=new ServerBootstrap();						//2创建辅助工具类,用于服务器通道的一系列配置
		b.group(pGroup,cGroup)											//绑定两个线程组
		.channel(NioServerSocketChannel.class)							//指定NIO的模式
		.option(ChannelOption.SO_BACKLOG,1024)							//设置TCP缓冲区
		.option(ChannelOption.SO_SNDBUF, 32*1024) 						//设置发送缓冲大小
		.option(ChannelOption.SO_RCVBUF,32*1024)						//设置接收缓冲大小
		.option(ChannelOption.SO_KEEPALIVE,true)						//保持连接
		.childHandler(new ChannelInitializer<SocketChannel>(){
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				sc.pipeline().addLast(new ServerHandler());				//3在这里配置具体数据接收方法的处理
				
			}
			
		});
		ChannelFuture cf1=b.bind(8765).sync(); 							//4进行绑定
		System.out.println("Server start 。。。。");
		cf1.channel().closeFuture().sync();								//5等待关闭
		pGroup.shutdownGracefully();									
		cGroup.shutdownGracefully();
		
	}

}
//ServerHandler 
package lqt.netty.helloworld;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter{
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf=(ByteBuf)msg;
        byte[] req=new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body=new String(req,"utf-8");
        System.out.println("Server:"+body);
        
        //服务器端给客户端的响应
        String response="hi Client";
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
    }
	
	 @Override
	    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	        ctx.close();
	    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

Client

package lqt.netty.helloworld;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
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.NioSocketChannel;

public class Client {

	public static void main(String[] args) throws Exception {
		EventLoopGroup group=new NioEventLoopGroup();
		Bootstrap b=new Bootstrap();
		b.group(group)
		.channel(NioSocketChannel.class)										//客户端用的NioSocketChannel
		.handler(new ChannelInitializer<SocketChannel>() {						//客户端用的handler

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				sc.pipeline().addLast(new ClientHandler());
				
			}
			
		});
		ChannelFuture cf1=b.connect("127.0.0.1",8765).sync();
		System.out.println("client connected....");
		
		cf1.channel().writeAndFlush(Unpooled.copiedBuffer("hello server".getBytes()));
		//.addListener(ChannelFutureListener.CLOSE)								//可以设置为短连接
		Thread.sleep(1000);
		cf1.channel().writeAndFlush(Unpooled.copiedBuffer("hello server".getBytes()));
		Thread.sleep(1000);
		
		
		cf1.channel().writeAndFlush(Unpooled.copiedBuffer("hello server".getBytes()));
		cf1.channel().closeFuture().sync();
		group.shutdownGracefully();
		

	}

}
//ClientHandler 
package lqt.netty.helloworld;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter {
	@Override
	
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {   
			ByteBuf bf=(ByteBuf)msg;
	        byte[] b=new byte[bf.readableBytes()];
	        bf.readBytes(b);
	        String body=new String(b,"utf-8");
	        System.out.println("Client: "+body);
	    }finally {
			ReferenceCountUtil.release(msg);
		}
	}
    
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("激活....");
    }
	
	@Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("读完毕...");
    }
	
	@Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注册完毕....");
        System.out.println(ctx.name());
    }
	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值