ITeye博客

netty和mina Socket框架(转)

eoasis · 2012-03-02 09:49 · Spring · 服务器配置 · 综合技术 · 开源软件 · Markdown

(转自:http://blog.163.com/chen_scor/blog/static/178805061201182615318929/)

比较:http://sandaobusi.iteye.com/blog/961175

从Jetty、Tomcat和Mina中提炼NIO构架Server的经典模式:

从Jetty、Tomcat和Mina中提炼NIO构架网络服务器的经典模式(一) 从Jetty、Tomcat和Mina中提炼NIO构架网络服务器的经典模式(二) 从Jetty、Tomcat和Mina中提炼NIO构架网络服务器的经典模式(三)

0.mina比netty出现的早,都是Trustin Lee的作品;

1.mina将内核和一些特性的联系过于紧密,使得用户在不需要这些特性的时候无法脱离,相比下性能会有所下降;netty解决了这个设计问题;

2.netty的文档更清晰,很多mina的特性在netty里都有;

3.netty更新周期更短,新版本的发布比较快;

4.它们的架构差别不大,mina靠apache生存,而netty靠jboss,和jboss的结合度非常高,netty有对google protocal buf的支持,有更完整的ioc容器支持(spring,guice,jbossmc和osgi);

5.netty比mina使用起来更简单,netty里你可以自定义的处理upstream events 或/和 downstream events,可以使用decoder和encoder来解码和编码发送内容;

6.netty和mina在处理UDP时有一些不同,netty将UDP无连接的特性暴露出来;而mina对UDP进行了高级层次的抽象,可以把UDP当成"面向连接"的协议,而要netty做到这一点比较困难。

运用spring注解实现netty服务器端udp应用程序

http://blog.csdn.net/tanrenzong1986/article/details/6404256

netty是JBOSS针对网络开发的一套应用框架,它也是在NIO的基础上发展起来的。netty基于异步的事件驱动,具有高性能、高扩展性等特性,它提供了统一的底层协议接口,使得开发者从底层的网络协议(比如 TCP/IP、UDP)中解脱出来。就使用来说,开发者只要参考 Netty提供的若干例子和它的指南文档,就可以放手开发基于Netty的服务端程序了。

netty有几个比较重要的概念,在此,仅做介绍,详细可以参考netty文档或源码。

1). channelBuffer: Bootstrap 是一个设置服务的帮助类。你甚至可以在这个服务中直接设置一个 Channel 通道。

现在以实现一个UDP协议下的服务器应用程序为例,演示netty通过spring注解开发服务器端。(在此以maven工具管理项目开发)

首先,是导入关联jar的POM文件:

  • expand sourceview plaincopy to clipboardprint?
    4.0.0
    com.byd.example
    nettyTest
    0.0.1-SNAPSHOT
    jar
    nettyTest
    http://maven.apache.org

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>



    junit
    junit
    3.8.1
    test


    slf4j
    slf4j-jdk14
    1.6.1


    log4j
    log4j
    1.2.9


    org.jboss.netty
    netty
    3.2.0.BETA1


    org.springframework
    spring-context
    3.0.2.RELEASE


    org.springframework
    spring-expression
    3.0.2.RELEASE


    org.springframework
    spring-tx
    3.0.2.RELEASE


    org.springframework
    spring-context
    3.0.2.RELEASE




    repository.jboss.org
    http://repository.jboss.org/nexus/content/groups/public/

    false



接下来是应用程序代码,在本人机器上可以运行并正常工作,如有需要可以试试。

I、Server接口:

view plaincopy to clipboardprint? package com.byd.example.netty;
public interface IServer
{
/** * 启动服务器 /
public void start();
/
* * 重启程序 */
public void restart();

/** 
 * 停止程序运行 
 */  
public void stop();  

}

II、ChannelHandler扩张类(继承SimpleChannelHandler):

view plaincopy to clipboardprint? package com.byd.example.netty;
import java.util.Random;
import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.DynamicChannelBuffer;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.springframework.stereotype.Component;
@Component("receiverHandler")
public class ReceiverHandler extends SimpleChannelHandler
{
private static final Logger logger=Logger.getLogger(ReceiverHandler.class.getName());

@Override  
public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception  
{  
    ChannelBuffer buffer=(ChannelBuffer)e.getMessage();  
    byte recByte=buffer.copy().toByteBuffer().array();  
    String recMsg=new String(recByte);  
    logger.info("server received:"+recMsg.trim());  
    Random random=new Random();  
    int backWord=random.nextInt(10000);  
    ChannelBuffer responseBuffer=new DynamicChannelBuffer(4);  
    responseBuffer.readBytes(backWord);  
    e.getChannel().write(responseBuffer);  
}  
  
@Override  
public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e)  
{  
    logger.error(e.getCause());  
    if(e.getChannel() !=null)  
    {  
        e.getChannel().close().addListener(ChannelFutureListener.CLOSE);  
    }  
}  

}

III、ChannelPipelineFactory实现类,包装ChannelHandler,处理I/O事件。

view plaincopy to clipboardprint? package com.byd.example.netty;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component("serverChannelPipelineFactory")
public class ServerChannelPipelineFactory implements ChannelPipelineFactory
{
@Autowired
@Qualifier("receiverHandler")
private ReceiverHandler handler;
@Override
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline=Channels.pipeline();
pipeline.addLast("handler", this.handler);
return pipeline;
}
public void setHandler(ReceiverHandler handler) {
this.handler = handler;
}
}

IV、Iserver接口的实现类。

  • expand sourceview plaincopy to clipboardprint? package com.byd.example.netty;
    import java.net.InetSocketAddress;
    import java.net.SocketAddress;
    import java.util.concurrent.Executors;
    import org.apache.log4j.Logger;
    import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
    import org.jboss.netty.channel.Channel;
    import org.jboss.netty.channel.ChannelFutureListener;
    import org.jboss.netty.channel.socket.DatagramChannelFactory;
    import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Component;
    @Component("serverNettyImpl")
    public class ServerNettyImpl implements IServer {
    @Autowired
    @Qualifier("serverChannelPipelineFactory")
    private ServerChannelPipelineFactory pipelineFactory;
    private Channel channel;
    private static final Logger logger = Logger.getLogger(ServerNettyImpl.class
    .getName());
    @Override
    public void start() {
    DatagramChannelFactory udpChannelFactory = new NioDatagramChannelFactory(
    Executors.newCachedThreadPool());
    ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(udpChannelFactory);
    bootstrap.setOption("reuseAddress", false);
    bootstrap.setOption("child.reuseAddress", false);
    bootstrap.setOption("readBufferSize", 1024);
    bootstrap.setOption("writeBufferSize", 1024);
    bootstrap.setPipelineFactory(this.pipelineFactory);
    SocketAddress serverAddress = new InetSocketAddress(5000);
    this.channel = bootstrap.bind(serverAddress);
    logger.info("server start on " + serverAddress);
    }
    @Override
    public void restart() {
    this.stop();
    this.start();
    }
    @Override
    public void stop() {
    if (this.channel != null) {
    this.channel.close().addListener(ChannelFutureListener.CLOSE);
    }
    }
    }

V、应用程序入口:

  • expand sourceview plaincopy to clipboardprint? package com.byd.example;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import com.byd.example.netty.IServer;
    public class NettyTestRun
    {
    public static void main( String args )
    {
    ApplicationContext context=new ClassPathXmlApplicationContext("classpath*:nettyTest-context.xml");
    IServer server=(IServer)context.getBean("serverNettyImpl");
    server.start();
    }
    }

VI、context配置文件:

  • expand sourceview plaincopy to clipboardprint?


<context:component-scan base-package="com.byd.example"/>
context:annotation-config/

VII、日志配置文件:

  • expand sourceview plaincopy to clipboardprint?

<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/' >





























<!-- 根logger的设置-->      
<root>      
    <priority value ="debug"/>      
    <appender-ref ref="CONSOLE"/>      
    <appender-ref ref="FILE"/>         
</root>      

</log4j:configuration>

整理上面的代码,运行起来,可以看到服务器侦听在5000端口并接受客户端的信息并返回一个int随机数。

后记:netty当然也可以应用在TCP和客户端的程序,具体的使用可以参考netty API文档。

评论(1)

  1. #1 楼 · asialee · 2013-02-20 19:12

    博主这块写的挺好的,我完全看了,不过我也写了一些关于编解码器的,请批评指正http://asialee.iteye.com/blog/1769508

评论功能维护中,当前仅展示历史评论。