手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Netty使用实例

[日期:2013-09-07] 来源:Linux社区  作者:Linux [字体:大 中 小]

第二个例子,实际应用中会用到这个,发送POJO类Persons [name=周杰伦123, age=31, salary=10000.44]

package com.wujintao.netty;

import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;

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

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
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.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.junit.Test;

/**
 * 用POJO代替ChannelBuffer
 */

class TimeServerHandler3 extends SimpleChannelHandler { 
 
    @Override 
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) 
            throws Exception { 
        Persons person = new Persons("周杰伦123",31,10000.44);
        ChannelFuture future = e.getChannel().write(person); 
        future.addListener(ChannelFutureListener.CLOSE); 
    } 
} 

class TimeClientHandler3 extends SimpleChannelHandler{ 
 
    @Override 
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) 
            throws Exception { 
     Persons person = (Persons)e.getMessage(); 
        System.out.println(person); 
        e.getChannel().close(); 
    } 
}

/**
 * FrameDecoder and ReplayingDecoder allow you to return an object of any type.
 *
 */
class TimeDecoder extends FrameDecoder { 
 private final ChannelBuffer buffer = dynamicBuffer();
 
    @Override 
    protected Object decode(ChannelHandlerContext ctx, Channel channel, 
            ChannelBuffer channelBuffer) throws Exception { 
        if(channelBuffer.readableBytes()<4) { 
            return null; 
        } 
        if (channelBuffer.readable()) {
   // 读到,并写入buf
         channelBuffer.readBytes(buffer, channelBuffer.readableBytes());
  }
        int namelength = buffer.readInt();
        String name = new String(buffer.readBytes(namelength).array(),"GBK");
        int age = buffer.readInt();
        double salary = buffer.readDouble();
        Persons person = new Persons(name,age,salary);
        return person; 
    } 
 
} 

class TimeEncoder extends SimpleChannelHandler { 
 private final ChannelBuffer buffer = dynamicBuffer();
 
    @Override 
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) 
            throws Exception { 
        Persons person = (Persons)e.getMessage(); 
        buffer.writeInt(person.getName().getBytes("GBK").length);
        buffer.writeBytes(person.getName().getBytes("GBK"));
        buffer.writeInt(person.getAge());
        buffer.writeDouble(person.getSalary());
        Channels.write(ctx, e.getFuture(), buffer); 
    } 
}

class Persons{
 private String name;
 private int age;
 private double salary;
 
 public Persons(String name,int age,double salary){
  this.name = name;
  this.age = age;
  this.salary = salary;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public double getSalary() {
  return salary;
 }
 public void setSalary(double salary) {
  this.salary = salary;
 }

 @Override
 public String toString() {
  return "Persons [name=" + name + ", age=" + age + ", salary=" + salary
    + "]";
 }
 
 
}

public class TestCase5 {
 public void testServer() {
    ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); 
        ServerBootstrap bootstrap = new ServerBootstrap(factory); 
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() { 
             
            public ChannelPipeline getPipeline() throws Exception { 
                return Channels.pipeline(new TimeEncoder(), new TimeServerHandler3()); 
            } 
        }); 
        bootstrap.setOption("child.tcpNoDelay", true); 
        bootstrap.setOption("child.keepAlive", true); 
         
        bootstrap.bind(new InetSocketAddress("localhost",9999));
 }
 
 public void testClient(){
  //创建客户端channel的辅助类,发起connection请求
  ClientBootstrap bootstrap = new ClientBootstrap(
    new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(),
      Executors.newCachedThreadPool()));
  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
   public ChannelPipeline getPipeline() {
    ChannelPipeline pipeline =  Channels.pipeline();
    pipeline.addLast("decoder", new TimeDecoder());
    pipeline.addLast("encoder", new TimeEncoder());
    pipeline.addLast("handler", new TimeClientHandler3());
    return pipeline;
   }
  });
  //创建无连接传输channel的辅助类(UDP),包括client和server
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(
    "localhost", 9999));
  future.getChannel().getCloseFuture().awaitUninterruptibly();
  bootstrap.releaseExternalResources();
 }

 @Test
 public void testNetty() {
   testServer();
   testClient();
 }
}

linux
相关资讯       Netty  Netty使用  Netty实例 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款