当前位置: 移动技术网 > IT编程>开发语言>.net > Netty入门二:开发第一个Netty应用程序

Netty入门二:开发第一个Netty应用程序

2018年12月07日  | 移动技术网IT编程  | 我要评论

既然是入门,那我们就在这里写一个简单的demo,客户端发送一个字符串到服务器端,服务器端接收字符串后再发送回客户端。

2.1、配置开发环境

1.安装jdk 2.去官网下载jar包 (或者通过pom构建) 2.2、认识下netty的client和server 一个netty应用模型,如下图所示,但需要明白一点的是,我们写的server会自动处理多客户端请求,理论上讲,处理并发的能力决定于我们的配置及jdk的极限。 vcxuo6y+zcrhus3jvb2owalby8g0vdojrmtjz/ljvbtzurdby9k7yfmjrl7ntpqx7c/yyb23osvnwcvk/b7do6ze47xeurdj+b6tuf3jvbxet7tj5ndos8nby7vyyfmjrnxiupa72mn5vs3kx7f+zvhg97xez+ztpsr9vt2ho8jnufve47/j0tta67+qo6y+zbt6se22z7+qwcvbtl3to6y1sci7xopssr/j0ttu2bvywlsho9k7tm6/ydluuvo6w7bgymvp8sm9tpo6skosy/vdx7xeurdj+dky0ru2qlvhtco1vcm9tcs72nomoamkcjxzdhjvbmc+mi4zinc00ru49k5ldhr5ifnlcnzlcjwvc3ryb25npgogicagink7upzozxr0evnlcnzlcrpm0plw99kq08nbvbk/t9bx6bpjo7okcgpcb290c1ryyxbwaw5nosxk1so3/s7xxve2y7v5sb7qxc+iu2vydmvysgfuzgxlcjrv5tx9tctstc7xwt+8rbsmwo0kphn0cm9uzz4yljmumsbcb290c1ryyxbwaw5ntcs5/bpmojwvc3ryb25npgo8chjlignsyxnzpq=="brush:java;">package nettydemo.echo.server; 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; import nettydemo.echo.handler.echoserverhandler; public class echoserver { private static final int port = 8080; public void start() throws interruptedexception { serverbootstrap b = new serverbootstrap();// 引导辅助程序 eventloopgroup group = new nioeventloopgroup();// 通过nio方式来接收连接和处理连接 try { b.group(group); b.channel(nioserversocketchannel.class);// 设置nio类型的channel b.localaddress(new inetsocketaddress(port));// 设置监听端口 b.childhandler(new channelinitializer() {//有连接到达时会创建一个channel protected void initchannel(socketchannel ch) throws exception { // pipeline管理channel中的handler,在channel队列中添加一个handler来处理业务 ch.pipeline().addlast("myhandler", new echoserverhandler()); } }); channelfuture f = b.bind().sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功 system.out.println(echoserver.class.getname() + " started and listen on " + f.channel().localaddress()); f.channel().closefuture().sync();// 应用程序会一直等待,直到channel关闭 } catch (exception e) { e.printstacktrace(); } finally { group.shutdowngracefully().sync();//关闭eventloopgroup,释放掉所有资源包括创建的线程 } } public static void main(string[] args) { try { new echoserver().start(); } catch (interruptedexception e) { e.printstacktrace(); } } } 1. 创建一个serverbootstrap实例
2. 创建一个eventloopgroup来处理各种事件,如处理链接请求,发送接收数据等。
3. 定义本地inetsocketaddress( port)好让server绑定
4. 创建childhandler来处理每一个链接请求
5. 所有准备好之后调用serverbootstrap.bind()方法绑定server
2.3.2 业务逻辑serverhandler:
要想处理接收到的数据,我们必须继承channelinboundhandleradapter接口,重写里面的messagereceive方法,每当有数据到达,此方法就会被调用(一般是byte类型数组),我们就在这里写我们的业务逻辑:
package nettydemo.echo.handler;

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;
/**
 * sharable表示此对象在channel间共享
 * handler类是我们的具体业务类
 * */
@sharable//注解@sharable可以让它在channels间共享
public class echoserverhandler extends channelinboundhandleradapter{
	public void channelread(channelhandlercontext ctx, object msg) { 
		system.out.println("server received data :" + msg); 
		ctx.write(msg);//写回数据,
	} 
	public void channelreadcomplete(channelhandlercontext ctx) { 
		ctx.writeandflush(unpooled.empty_buffer) //flush掉所有写回的数据
		.addlistener(channelfuturelistener.close); //当flush完成后关闭channel
	} 
	public void exceptioncaught(channelhandlercontext ctx,throwable cause) { 
		cause.printstacktrace();//捕捉异常信息
		ctx.close();//出现异常时关闭channel 
	} 	
}

2.3.3关于异常处理:
我们在上面程序中也重写了exceptioncaught方法,这里就是对当异常出现时的处理。
2.4 写一个netty client
一般一个简单的client会扮演如下角色: 连接到server向server写数据等待server返回数据关闭连接 4.4.1 bootstrapping的过程:
和server端类似,只不过client端要同时指定连接主机的ip和port。
package nettydemo.echo.client;

import io.netty.bootstrap.bootstrap;
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;

import java.net.inetsocketaddress;

import nettydemo.echo.handler.echoclienthandler;

public class echoclient {
	private final string host;
	private final int port;

	public echoclient(string host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws exception {
		eventloopgroup group = new nioeventloopgroup();
		try {
			bootstrap b = new bootstrap();
			b.group(group);
			b.channel(niosocketchannel.class);
			b.remoteaddress(new inetsocketaddress(host, port));
			b.handler(new channelinitializer() {

				public void initchannel(socketchannel ch) throws exception {
					ch.pipeline().addlast(new echoclienthandler());
				}
			});
			channelfuture f = b.connect().sync();
			f.addlistener(new channelfuturelistener() {
				
				public void operationcomplete(channelfuture future) throws exception {
					if(future.issuccess()){
						system.out.println("client connected");
					}else{
						system.out.println("server attemp failed");
						future.cause().printstacktrace();
					}
					
				}
			});
			f.channel().closefuture().sync();
		} finally {
			group.shutdowngracefully().sync();
		}
	}

	public static void main(string[] args) throws exception {
	
		new echoclient("127.0.0.1", 3331).start();
	}
}
1. 创建一个serverbootstrap实例
2. 创建一个eventloopgroup来处理各种事件,如处理链接请求,发送接收数据等。
3. 定义一个远程inetsocketaddress好让客户端连接
4. 当连接完成之后,handler会被执行一次
5. 所有准备好之后调用serverbootstrap.connect()方法连接server 4.4.2 业务逻辑clienthandler:
我们同样继承一个simplechannelinboundhandler来实现我们的client,我们需要重写其中的三个方法:
package nettydemo.echo.handler;

import io.netty.buffer.bytebuf;
import io.netty.buffer.bytebufutil;
import io.netty.buffer.unpooled;
import io.netty.channel.channelhandlercontext;
import io.netty.channel.simplechannelinboundhandler;
import io.netty.channel.channelhandler.sharable;
import io.netty.util.charsetutil;

@sharable
public class echoclienthandler extends simplechannelinboundhandler {
	/**
	 *此方法会在连接到服务器后被调用 
	 * */
	public void channelactive(channelhandlercontext ctx) {
		ctx.write(unpooled.copiedbuffer("netty rocks!", charsetutil.utf_8));
	}
	/**
	 *此方法会在接收到服务器数据后调用 
	 * */
	public void channelread0(channelhandlercontext ctx, bytebuf in) {
		system.out.println("client received: " + bytebufutil.hexdump(in.readbytes(in.readablebytes())));
	}
	/**
	 *捕捉到异常 
	 * */
	public void exceptioncaught(channelhandlercontext ctx, throwable cause) {
		cause.printstacktrace();
		ctx.close();
	}

}

其中需要注意的是channelread0()方法,此方法接收到的可能是一些数据片段,比如服务器发送了5个字节数据,client端不能保证一次全部收到,比如第一次收到3个字节,第二次收到2个字节。我们可能还会关心收到这些片段的顺序是否可发送顺序一致,这要看具体是什么协议,比如基于tcp协议的字节流是能保证顺序的。 还有一点,在client端我们的业务handler继承的是simplechannelinboundhandler,而在服务器端继承的是channelinboundhandleradapter,那么这两个有什么区别呢?最主要的区别就是simplechannelinboundhandler在接收到数据后会自动release掉数据占用的bytebuffer资源(自动调用bytebuffer.release())。而为何服务器端不能用呢,因为我们想让服务器把客户端请求的数据发送回去,而服务器端有可能在channelread方法返回前还没有写完数据,因此不能让它自动release。


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网