Netty3 入门HelloWorld

1、Netty:可应用与分布式进程通信,例如:hadoop、dubbo、akka等具有分布式的框架,底层RPC通信都是基于netty实现的。
2、Netty:入门 HelloWorld 代码如下,具体有注释说明。

public class ServerSocket {
	/*
	 * netty 服务helloworld
	 * @author :zhengzx
	 * 
	 */
	public static void main(String[] args) {
		//创建服务类
		ServerBootstrap bootstrap = new ServerBootstrap();
		
		//创建两个线程池
		//boss线程监听窗口
		ExecutorService boss = Executors.newCachedThreadPool();
		//worker负责数据读写
		ExecutorService worker = Executors.newCachedThreadPool();
		
		//设置nioSocket工厂
		bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));
		
		//设置管道的工厂
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				//创建管道
				ChannelPipeline pipeline = Channels.pipeline();
				//将管道中的二进制转换为String,读取的时候
				pipeline.addLast("deCode", new StringDecoder());
				//将String转化为二进制,进行管道传送
				pipeline.addLast("enCode", new StringEncoder());
				//处理消息的实体类(需要继承simpleChannelHandler,实现相关的方法)
				pipeline.addLast("helloWorldHandler", new HelloWorldHandler());
				return pipeline;
			}
		});
		
		//绑定连接端口
		bootstrap.bind(new InetSocketAddress(8000));
		
		System.out.println("服务端启动成功");
	}
}

3、实际业务处理的 handler 类

package com.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
//实现SimpleChannelHandler类后,可以通过Alt+Shift+M点击override选择需要重写的方法。
public class HelloWorldHandler extends SimpleChannelHandler{
	//客户端关闭时
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.channelClosed(ctx, e);
	}
	//客户端连接时
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("用户连接成功");
		super.channelConnected(ctx, e);
	}
	//客户端端来连接时
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("用户断开连接");
		super.channelDisconnected(ctx, e);
	}
	//发生异常时
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, e);
	}
	//重要:接受消息和发送消息处理方法
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		//接受消息,decode以将二进制消息进行转换
		Object message = e.getMessage();
		System.out.println(message);
		//返回success,encode以帮助处理为二进制消息
		ctx.getChannel().write("success");
		super.messageReceived(ctx, e);
	}

}

4、测试方法:通过cmd——>输入telnet 127.0.0.1 8000——>Ctrl+]——>send HelloWorld——>Enter——>显示输出消息。

Netty3 入门HelloWorld_第1张图片

5、上面测试成功,说明服务端完成,接着完成客户端代码:(handler 类与服务端基本相同)

public class ClientSocket {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//创建客户端的服务类
		ClientBootstrap clientBootstrap = new ClientBootstrap();
		
		//创建两个线程池,与服务端相同
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		
		//创建Socket工厂
		clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));
		
		//创建管道工厂
		clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				//创建管道
				ChannelPipeline pipeline = Channels.pipeline();
				//添加handler
				pipeline.addLast("encode", new StringEncoder());
				pipeline.addLast("decode", new StringDecoder());
				pipeline.addLast("successHandler", new SuccessHandler());
				return pipeline;
			}
		});
		
		//连接服务器
		ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
		//获取通道
		 Channel channel = connect.getChannel();
		System.out.println("客户端已连接");
		
		//写入数据
		@SuppressWarnings("unused")
		Scanner scanner = new Scanner(System.in);
		while(true ) {
			System.out.println("请输入:");
			channel.write(scanner.next());
		}
		
	}
}


 ----关注公众号,获取更多内容---- 

你可能感兴趣的:(Netty)