Netty简单socket通信

Netty版本:netty-all-4.0.52.Final.jar

1.服务端

package com.sunlei.netty.server;

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

public class TimeServer {

	public static void main(String[] args) throws Exception {
		new TimeServer().bind(8888);

	}

	private void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try{
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new ChildChannelHandler());
			
			ChannelFuture f = b.bind(port).sync();
			f.channel().closeFuture().sync();
		}finally{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}		
	}
}

代码分析:

(1)NioEventLoopGroup是Reactor线程组,这里创建两个线程组实例来用作网络事件的处理,一个用于服务端接受客户端的连接,一个用于进行SocketChannel的网络读写。

(2)创建ServerBootstrap对象目的是降低服务端的开发复杂度,是用于启动NIO服务端的辅助启动类。

(3)调用group()方法,将两个NIO线程组当作参数传入到ServerBootstrap中。

(4)创建Channel为NioServerSocketChannel,配置它的TCP参数,服务端启动辅助类配置完成。

(5)调用bind()方法绑定监听端口,调用同步阻塞方法sync等待绑定操作完成。

package com.sunlei.netty.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel arg0) throws Exception {
		arg0.pipeline().addLast(new TimeServerHandler());		
	}

}


package com.sunlei.netty.server;

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

public class TimeServerHandler extends ChannelInboundHandlerAdapter {
	
	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("The time server receive order:"+body);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
				System.currentTimeMillis()).toString() : "BAD ORDER";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.writeAndFlush(resp);
	}
	
	public void channnelReadComplete(ChannelHandlerContext ctx){
		ctx.flush();
	}

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

代码分析:

    这里主要做业务逻辑处理,对网络事件进行读写操作,主要是channelRead()方法。

(1)通过ByteBuf的readableBytes()方法可以获取缓冲区可读的字节数,根据可读的字节数创建byte数组,通过ByteBuf的readBytes()方法将缓冲区中的字节数组复制到新建的byte数组中,最后通过new String构造方法获取请求信息。对请求信息进行判断,如果是的所要求的则创建应答消息,通过ChannelHandlerContext的write方法异步发送应答消息给客户端。

(2)将msg转换成Netty的ByteBuf对象,ChannelHandlerContext的flush()方法的作用是将消息发送队列中的消息写入到SocketChannel中发送给对方,这是为了防止频繁地唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中,调用write方法只是把待发送的消息放到缓冲数组中,再通过调用flush方法,将发送缓冲区中的消息全部写到SocketChannel中。

(3)当发生异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源。


2.客户端

package com.sunlei.netty.client;

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

public class TimeClient {

	public static void main(String[] args) throws Exception {
		new TimeClient().connect(8888,"127.0.0.1");
	}

	private void connect(int port, String host) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try{
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer());
			
			ChannelFuture f = b.connect(host,port).sync();	
			f.channel().closeFuture().sync();
			
		}finally{
			group.shutdownGracefully();
		}		
	}
}

代码解析:

(1)创建NioEventLoopGroup线程组来处理客户端I/O读写,创建客户端辅助启动类Bootstrap,这里的Channel需要设置为NioSocketChannel。

(2)设置完成,调用connect()方法发起异步连接,然后调用同步方法等待连接成功。

package com.sunlei.netty.client;

import io.netty.channel.socket.SocketChannel;

public class ChannelInitializer extends io.netty.channel.ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel sc) throws Exception {
		sc.pipeline().addLast(new TimeClientHandler());
	}
}


package com.sunlei.netty.client;

import java.util.logging.Logger;

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

public class TimeClientHandler extends ChannelInboundHandlerAdapter {
	
	private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
	private final ByteBuf firstMessage;
	
	public TimeClientHandler(){
		byte[] req = "QUERY TIME ORDER".getBytes();
		firstMessage = Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
	}
	
	public void channelActive(ChannelHandlerContext ctx){
		ctx.writeAndFlush(firstMessage);
	}
	
	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("Now is :"+body);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warning("Unexpected exception from downstream:"+cause.getMessage());
		ctx.close();
	}
}

代码解析:

当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法,发送查询时间的指令给服务端,调用ChannelHandlerContext的writeAndFlush方法将请求消息发送给服务端。当服务端返回应答消息时,channelRead方法被调用。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值