本文主要是介绍MINA实现长连接的关键配置,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用MINA进行通讯时,如需服务器及客户端一直在线,则需要创建并维护长连接。在MINA中通过如下设置即可:
acceptor.getFilterChain().addLast("keeplive", new KeepAliveFilter(new ServerKeepAliveMessageFactoryImp(), IdleStatus.BOTH_IDLE, KeepAliveRequestTimeoutHandler.CLOSE,4, 50));
其中IdleStatus.BOTH_IDLE为空闲时的状态标识,官方介绍如下:
IdleStatus表示IoSession
或者 IoSession
的空闲类型,有如下三种:
READER_IDLE
- 没有来自客户端的数据(读空闲)WRITER_IDLE
- Session空闲(等待写入)BOTH_IDLE
- 以上两种都空闲
KeepAliveRequestTimeoutHandler.CLOSE设置超时关闭
通过添加KeepAliveMessageFactory实现类实现KeepAliveMessageFactory接口,代码如下:
package mina;import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
/*** * @author liangxin* @created 2020-09-12**/
public class ServerKeepAliveMessageFactoryImp implements KeepAliveMessageFactory{public boolean isRequest(IoSession session, Object message) {// TODO Auto-generated method stubif(message instanceof String && message.equals("ping")){return true;}return false;}public boolean isResponse(IoSession session, Object message) {// TODO Auto-generated method stub
// if(message instanceof String && message.equals("pong")){
// return true;
// }return false;}public Object getRequest(IoSession session) {// TODO Auto-generated method stubreturn "server";}public Object getResponse(IoSession session, Object request) {// TODO Auto-generated method stubreturn "client";}}
这篇关于MINA实现长连接的关键配置的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!