开发一套稳定高效客户端-服务端Socket通讯服务不是一件很简单的事。 这几天试用了一下Netty2(http://gleamynode.net/dev/projects/netty2/) 我们在做短信应用开发中,经常会碰到与移动、联通、小灵通网关进行Socket通讯,厂商提供的API效率不高,而自己开发的API费时、费力,花费了不少时间,稳定性还经常无法保证。 使用了Netty2,一方面能使开发框架更加清晰,也减少了不少开发时间。下面简单举个开发与小灵通短信网关通讯API的例子。 小灵通短信协议于SMPP、CMPP类似: 下面举例如何使用Netty实现此通讯协议: |
介绍一个很好用的NIO Socket开发框架--Netty2
最新推荐文章于 2024-07-14 02:22:25 发布
1、实现Netty的MessageRecognizer 接口
由于精力原因,只在这实现Login,LoginRep数据包
2、实现通讯的协议包(PHSLogin,PHSLoginRep),需要继承Netty的Message接口,在这里由于协议包中有很多地方可以被抽象,所以还定义了一个PHSMessage的抽象类(在被注释的代码中,还残留了一些未用Netty之前自己用jdk io类时残留的一些代码 )
OK,完成这三个类,对于Socket流数据与Message对象的转换都已完成。以后就是根据协议增加相应的Message类即可。
下面看看如何运行让它工作起来,实现Netty的SessionListener 接口,网络连接成功、信息接收、网络断开事件都可知晓:
最后。写个Example类去运行:
下一步,考虑如何将它 与 Spring 结合起来,成为Spring的一个组件。相信这做起来一定很简单
Netty2是一个不错的NIO框架。另外如果有兴趣的话,你可以试一下http://sourceforge.net/projects/cindy/,支持SocketChannel/ServerSocketChannel/DatagramChannel/Pipe,还模拟了MulticastChannel,使得应用可以用同一个模型访问TCP/UDP。
THX,我去试试看看,主要目的是想找到一个开发IM软件服务端的网络通讯框架。
Cindy 怎么这么象 Netty?
Cindy最主要的构想是读完Java NIO这本书中的一个例子产生的,随后查找了当时所能够找到的Opensource的NIO实现,Netty2也是其中之一,所以Cindy中MessageRecognizer这个类其实是从Netty2中学习到的。
但是我对NIO的理解和Netty2有所不一样,要不就加入它的开发组了:)从Cindy 1.0版本可以看出,其实Cindy 1.0支持多种基于NIO的模型。但经过几个实际项目的考验,我发觉一些模型在实际使用中并没有什么优势,所以经过精简后保留了最常用的,并加入了UDP和Pipe的支持。
Cindy是从http://sourceforge.net/projects/java-jml中抽取出来的,最早它只是用来做这个MSN类库的基础平台,因为我的项目中单独使用这个NIO框架比较多,就把它抽取到Cindy这个项目中来了。
高啊。。我看不懂。。
以前置只写些同步超时模式的socket,省事,还是用python编造的。协议也是自己定的。
看到那些一坨坨没有注释的代码就发怵。如果有有幸开发短信程序可以好好参照一下。。
想前些时开发收发短信程序,和wavecom 240x打交道(串口),在兄弟指点下还摸了一周。。
哈哈,你也在做MSN类库?我们已经做了一年的MSN应用(使用韩国人写的那个msnmlib),灵犀短信精灵(smsbot448@sms107.com)是我们提供的服务。
在msnmlib的基础上,我们修改了代码,将协议支持到MSNP10,进一步提升了稳定性。另外为了方便应用开发,还附加开发了一个msnapp-engine。
这段时间从降低硬件成本投入考虑,也想从msn底层包入手进一步进行一次修改。
我的mail是 newjoy@gmail.com 以后还希望能多交流。
如何使用netty编写一个程序和服务器一直都保持连接,同时,使用一个线程隔时扫描一个队列,把队列新增的消息逐一发送出去?
看了看netty提供的例子。它使用session来管理会话,SessionListener的connectionEstablished()来发送消息,session.start()来触发整个流程,监听器捕获到时间后执行发送和接收。
监听的线程不能直接写在connectionEstablished()吧?那应该怎么处理呢?netty提供了接口吗?