Netty框架解读

来源:互联网 发布:淘宝h5页面如何提取 编辑:程序博客网 时间:2024/05/29 10:27
netty框架有服务器端和客户端
步骤:
1、导入jia包(客户端和服务器都需要的)

一、服务器端:

Server.java

package com.angela.cc;

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

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class Server
{
public static void main(String[] args) throws Exception
{
// 申明,这里有两个线程池(一个是主线程,一个是工作线程池)
System.out.println("1111111111111111111111111111");
ServerBootstrap bootstrap=new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), 
Executors.newCachedThreadPool())
);
//这里是设置pipline,它的行为促发,是由Netty客户端促发的。当netty客户端启动的时候,这里开始行动,
// 会跳转到ServerHandler里面开始执行,具体执行过程,还需到ServerHandler里面去看

bootstrap.setPipelineFactory(new ChannelPipelineFactory()
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
System.out.println("222222222222222222222");

return Channels.pipeline(new ServerHandler());
}
});
System.out.println("3333333333333333333333");
//这个是Netty的服务器的启动(端口号设置为8080)
bootstrap.bind(new InetSocketAddress(8080));

}
}

ServerHandler.java

package com.angela.cc;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class ServerHandler extends SimpleChannelUpstreamHandler
{
private static final Logger logger = Logger.getLogger(ServerHandler.class
.getName());

    private final AtomicLong transferredBytes = new AtomicLong();

    public long getTransferredBytes()
    {
    System.out.println("serverHandler----------------------------》1");

        return transferredBytes.get();
    }

@Override
// 接收到客户端的消息
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception
{
// super.messageReceived(ctx, e);
    System.out.println("serverHandler----------------------------》2");

transferredBytes.addAndGet(((ChannelBuffer) e.getMessage())
.readableBytes());
e.getChannel().write(e.getMessage());
// 这里打印消息,只是想查看e.getMesage到底是什么
    System.out.println(e.getMessage());

e.getChannel().close();
}

@Override
// 捕获异常
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception
{
    System.out.println("serverHandler----------------------------》3");

// super.exceptionCaught(ctx, e);
logger.log(Level.WARNING, "Unexpected exception from downstream.",
e.getCause());
e.getChannel().close();
}
}

执行过程图解



二、客户端

Client.java

package com.angela.cc;

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

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class Client
{
public static void main(String[] args) throws Exception
{
// 定义一个值
final int fristMessagesize;
// 这里的参数值,用途是是可以设置线程池绑定的IP和端口号。但是来源,我不知道。所以下面绑定的是我设定的
if (args.length == 3)
{
fristMessagesize = Integer.parseInt(args[2]);
} else
{
fristMessagesize = 256;
}
System.out.println("Client------------->1");
// 开启线程池,一个主线程池,一个工作线程池
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
System.out.println("Client------------->2");
//        可以访问ClientHandler
bootstrap.setPipelineFactory(new ChannelPipelineFactory()
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
System.out.println("Client------------->3");

return Channels.pipeline(new ClientHandler(fristMessagesize));
}
});
System.out.println("Client------------->4");
//          连接到IP为192.168.1.119,端口号为8080的机器
ChannelFuture Future = bootstrap.connect(new InetSocketAddress(
"192.168.1.119", 8080));
System.out.println("Client------------->5");
//连接完之后进行关闭(等待完成后再关闭)
Future.getChannel().getCloseFuture().awaitUninterruptibly();
System.out.println("Client------------->6");
//释放资源
bootstrap.releaseExternalResources();
System.out.println("Client------------->7");

}
}


ClientHandler.java

package com.angela.cc;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
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.SimpleChannelUpstreamHandler;

public class ClientHandler extends SimpleChannelUpstreamHandler
{
private static final Logger logger = Logger.getLogger(ClientHandler.class
.getName());

private final ChannelBuffer fristmessage;

private final AtomicLong transferredBytes = new AtomicLong();

public ClientHandler(int fristmessagesize)
{
if (fristmessagesize <= 0)
{
throw new IllegalArgumentException("firstMessageSize: "
+ fristmessagesize);
}
fristmessage = ChannelBuffers.dynamicBuffer(fristmessagesize);
ChannelBuffers.buffer(2);
System.out.println(fristmessage);
for (int i = 0; i < fristmessage.capacity(); i++)
{
fristmessage.writeByte((byte) i);
}
System.out.println("ClientHandler-------------->1");
}

public long getTransferredBytes()
{
System.out.println("ClientHandler-------------->2");

return transferredBytes.get();
}

@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception
{
System.out.println("ClientHandler-------------->3");

super.channelConnected(ctx, e);
e.getChannel().write(fristmessage);
}

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception
{
System.out.println("ClientHandler-------------->4");

super.messageReceived(ctx, e);
transferredBytes.addAndGet(((ChannelBuffer) e.getMessage())
.readableBytes());
e.getChannel().write(e.getMessage());
e.getChannel().close();

}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception
{
System.out.println("ClientHandler-------------->5");

super.exceptionCaught(ctx, e);
logger.log(Level.WARNING, "Unexpected exception from downstream.",
e.getCause());
e.getChannel().close();
}

}

执行客户端图解:


jar包:
netty-3.2.3.Final.jar

原创粉丝点击