netty 3.0のサービスとクライアントの構築


もっと読む
 
説明を書くのが嫌いです。基本的には手順を使います。注意事項はコードコメントに書いてあります。関連する内容はネット上にたくさんあります。自分の理解よりもっといいです。だから、自分がある知識点に対する理解はメモに書いてあります。
1、業務上の編纂
package com.netty.helloserver;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

/**
 * @author Chalmers 2016 2 18    6:49:57
 */
public class NettyServer {

	public static void main(String[] args) {
		//        
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		//        
		//     ,  boss    ,worker   selector(NIO   )
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		//     ,            
		//    ,    netyy3.0   ,5.0   
		serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss,
				worker));
		//       
		serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

			@Override
			public ChannelPipeline getPipeline() throws Exception {

				ChannelPipeline channelPipeline = Channels.pipeline();
				//       , Handler           ,     ChannelBuffer 
				//      ,decoder        
				channelPipeline.addLast("decoder", new StringDecoder());
				// encoder        
				channelPipeline.addLast("encoder", new StringEncoder());
				/**
				 *      ,decoder encoder    ,        
				 */
				channelPipeline.addLast("helloHandler", new ServerHandler());
				//   
				return channelPipeline;
			}
		});

		//       ,    ,        ,      
		serverBootstrap.bind(new InetSocketAddress(9090));
		System.out.println("start --> server");

	}
}

class ServerHandler extends SimpleChannelHandler {

	/**
	 *         ,    
	 */
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelClosed(ctx, e);
		System.out.println("channelClosed");
	}

	/**
	 *         
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelConnected(ctx, e);
		System.out.println("channelConnected");
	}

	/**
	 *         ,       
	 */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		super.channelDisconnected(ctx, e);
		System.out.println("channelDisconnected");
	}

	/**
	 *     
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		super.exceptionCaught(ctx, e);
		System.out.println("exceptionCaught");
	}

	/**
	 *     
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.messageReceived(ctx, e);
		System.out.println("messageReceived");
		//           ,   StringDecode,           
		//          ,        
		// ChannelBuffer message = (ChannelBuffer) e.getMessage();
		// System.out.println(new String(message.array()));

		System.out.println(e.getMessage());

		/*
		 *     
		 */
		// ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("hi"
		// .getBytes());
		// ctx.getChannel().write(copiedBuffer);

		//          encoder,         ,       
		ctx.getChannel().write("hi");
	}

}
 
 
2、クライアントの作成
package com.netty.hiclient;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

/**
 * @author Chalmers 2016 2 18    10:22:08
 */
public class NettyClient {

	private static ClientBootstrap clientBootstrap;

	public static void main(String[] args) {
		//        
		clientBootstrap = new ClientBootstrap();

		//        
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();

		//     ,      
		clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss,
				worker));
		//       
		clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline channelPipeline = Channels.pipeline();
				//     
				channelPipeline.addLast("decoder", new StringDecoder());
				channelPipeline.addLast("encoder", new StringEncoder());
				channelPipeline.addLast("hiHandler", new ClientHandler());
				return channelPipeline;
			}
		});

		System.out.println("start --> client");
		//     ,       connect,   bind
		ChannelFuture channelFuture = clientBootstrap
				.connect(new InetSocketAddress("127.0.0.1", 9090));
		//    future   channel
		Channel channel = channelFuture.getChannel();
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.print("  : ");
			//    channel    
			channel.write(sc.next());
		}
	}
}

class ClientHandler extends SimpleChannelHandler {

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelClosed(ctx, e);
		System.out.println("channelClosed");
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelConnected(ctx, e);
		System.out.println("channelConnected");
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		super.channelDisconnected(ctx, e);
		System.out.println("channelDisconnected");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		super.exceptionCaught(ctx, e);
		System.out.println("exceptionCaught");
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.messageReceived(ctx, e);
		System.out.println("messageReceived");
		System.out.println(e.getMessage());
	}

}