最顶层父基类Clinet:用于记录公共内容

切供多个Clinet继承公用

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Timer;
import java.util.TimerTask; import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector; import com.qinghuainvest.tsmarket.codec.HCoderFactory;
import com.qinghuainvest.tsmarket.socketclient.MinaClientHanlder; /**
* 父基类
* @author huage
*
*/
public abstract class MinaBaseClient { public abstract void startSocketReq(String code);
protected String hostName ;
protected int bindPort; /**
* 创建IOSession
* @return
*/
protected IoSession createSession(){
if( StringUtils.isBlank(hostName)) return null;
try {
NioSocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
chain.addLast("objectFilter", new ProtocolCodecFilter(new HCoderFactory(Charset.forName("UTF-8"))));
MinaClientHanlder handler = new MinaClientHanlder();
connector.setHandler(handler);
connector.getSessionConfig().setUseReadOperation(true);
ConnectFuture cf = connector.connect(new InetSocketAddress(hostName, bindPort));
cf.awaitUninterruptibly();
return cf.getSession();
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 传输数据
* @param session
* @param code
*/
protected void writeMina(IoSession session,String code){
if( session == null )return;
session.write(code + "\n");
} public static void main(String[] args) {
Integer cacheTime = 1000 * 1;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
/*StockMina1004Client ns = new StockMina1004Client("218.1.111.62", 10003);
ns.startSocketReq(EmCommunicationCode.nqxx.getCode()+"" );*/
}
}, 1000, cacheTime);
}
}

子类继承

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class StockMinaClient extends MinaBaseClient{
private final Logger log = LoggerFactory.getLogger(StockMinaClient.class);
private boolean isStatus = true;
private IoSession session; public StockMinaClient(String hostName,int bindPort){
super.hostName = hostName;
super.bindPort = bindPort;
} public void startSocketReq(String code) {
if (isStatus) {
isStatus = false;
log.info("socket request start....hostName="+hostName+";bindPort="+bindPort+";requestparam="+code);
if (session == null || !session.isConnected()) {
session = createSession();
}
isStatus = true;
super.writeMina(session, code);
}
} }

子类重写(只是表明可以区别创建的对象)

import java.net.InetSocketAddress;
import java.nio.charset.Charset; import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector; import com.qinghuainvest.tsmarket.codec.HCoderFactory;
import com.qinghuainvest.tsmarket.socketclient.MinaClient1004Hanlder; public class StockMina1004Client extends StockMinaClient{
public StockMina1004Client(String hostName, int bindPort) {
super(hostName, bindPort);
} protected IoSession createSession(){
if( StringUtils.isBlank(hostName)) return null;
try {
NioSocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
chain.addLast("objectFilter", new ProtocolCodecFilter(new HCoderFactory(Charset.forName("UTF-8"))));
MinaClient1004Hanlder handler = new MinaClient1004Hanlder();
connector.setHandler(handler);
connector.getSessionConfig().setUseReadOperation(true);
ConnectFuture cf = connector.connect(new InetSocketAddress(hostName, bindPort));
cf.awaitUninterruptibly();
return cf.getSession();
} catch (Exception e) {
e.printStackTrace();
}
return null;
} }

需要的handler(根据实际业务调整messageReceived方法中的内容既可)

import java.util.Set;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class MinaClientHanlder extends IoHandlerAdapter {
private final Logger log = LoggerFactory.getLogger(MinaClientHanlder.class);
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
} @Override
public void messageReceived(IoSession session, Object message)throws Exception {
log.info("收到行情服务器回调传送数据...");
if (message != null) {
try {
callback((String) message,session);
clear(session);
} catch (Exception e) {
log.error("message Received ", e);
//e.printStackTrace();
session.write("system error.");
}
}
} public void callback(String msg,IoSession session){
if (!"null".equals(msg)) {
//处理数据
}
} /**
* 清除session中的attribute
* 解决mina通讯中内存溢出异常
* 测试方法,未找到明确依据
* @param session
*/
private void clear(IoSession session) {
Set<Object> set = session.getAttributeKeys();
if(set==null || set.size()==0) return;
for (Object object : set) {
if(session.containsAttribute(object)) {
session.removeAttribute(object);
}
}
}
@Override
public void sessionCreated(IoSession session) throws Exception {
log.info("session Created--");
//System.out.println("session Created");
}
@Override
public void messageSent(org.apache.mina.core.session.IoSession session, java.lang.Object message) {
log.info("message Sented");
//System.out.println("message Sented--");
}
}

根据业务需要的另一个handler

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MinaClient1004Hanlder extends MinaClientHanlder {
private final Logger log = LoggerFactory.getLogger(MinaClient1004Hanlder.class);public void callback(String msg,IoSession session) {
if (!"null".equals(msg)) {
//处理数据
}
startCheck();
} }

特殊业务处理的工具类(根据业务自行处理)

package com.qinghuainvest.tsmarket.codec;

import java.nio.charset.Charset;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder; public class HCoderFactory implements ProtocolCodecFactory { private final HDecoder decoder;
private final HEncoder encoder;
// private final TextLineEncoder encoder; public HCoderFactory() {
this(Charset.defaultCharset());
} public HCoderFactory(Charset charset) {
decoder = new HDecoder();
encoder = new HEncoder();
// encoder = new TextLineEncoder();
} public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
} public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
}
}
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput; public class HDecoder extends CumulativeProtocolDecoder { @Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
// Remember the initial position.
int start = in.position();
// byte previous = 0;
byte[] requestMsgArray;
while (in.hasRemaining()) {
byte current = in.get();
if (current == '\n') {
// Remember the current position and limit.
int position = in.position();
int limit = in.limit();
try {
int dataLength = position - start - 1;//忽略掉\n,所以减1
in.position(start);
in.limit(position);
requestMsgArray = new byte[dataLength];
// The bytes between in.position() and in.limit()
// now contain a full CRLF terminated line.
in.get(requestMsgArray);
out.write(new String(requestMsgArray));
} finally {
// Set the position to point right after the
// detected line and set the limit to the old
// one.
in.position(position);
in.limit(limit);
}
// Decoded one line; CumulativeProtocolDecoder will
// call me again until I return false. So just
// return true until there are no more lines in the
// buffer.
// previous = current;
return true;
}
}
in.position(start); return false; }
}
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput; public class HEncoder extends ProtocolEncoderAdapter { public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
String msg = (String) message;
byte[] msgArray = msg.getBytes();
IoBuffer buffer = IoBuffer.allocate(msgArray.length , false);
buffer.put(msgArray);
buffer.flip();
out.write(buffer);
out.flush();
}
}

处理调用启动写main方法调用

 public void start(){
   StockMinaClient client = null;
if( client == null ){
client = new StockMinaClient(market.getHostName(), market.getBindPort());
}
client.startSocketReq(EmCommunicationCode.nqxx.getCode()+"");
}

mima开发实列的更多相关文章

  1. AD域控Dsquery查询命令实列

    注:请以管理员的身份运行cmd程序,要不然某些命令不生效 AD域控Dsquery查询命令实列 查询技术支持二部的所有用户          dsquery user OU=技术支持二部,OU=技术部, ...

  2. jeecms系统使用介绍——通过二次开发实现对word、pdf、txt等上传附件的全文检索

    转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/76912307 本文出自[我是干勾鱼的博客] 之前在文章<基于Java的门户 ...

  3. Android系统开发实务实训

    实训项目 :               Android系统开发实务实训                           项目成品名称:         绝地坦克                 ...

  4. Flask常用实列化参数

    Flask中实列化配置: app = Flask( __name__, template_folder=’temp’ , ...... ) >template_folder = "te ...

  5. XML建模实列

    XML建模 建模的由来: 就是将指定的xml字符串当作对象来操作           好处在于,只需要调用指定的方法就可以完成预定的字符串获取: 建模的一个思路: 1.分析需要被建模的文件中有那几个对 ...

  6. docker中启动2个mysql实列

    一.mac环境安装docker容器 在docker官网中下载docker容器,地址:https://www.docker.com/products/docker-desktop 具体安装教程及设置网络 ...

  7. 实列+JVM讲解类的实列化顺序

    刨根问底---类的实列化顺序 开篇三问 1什么是类的加载,类的加载和类的实列有什么关系,什么时候类加载 2类加载会调用构造函数吗,什么时候调用构造函数 3什么是实列化对象,实列化的对象有什么东西. 我 ...

  8. 美化传奇NPC对话框添加图片显示实列

    NPC对话框一般都是文字显示,有些GM想突出版本特色,在NPC对话框加些专业图片,彰显独特之处,其实这是很简单的.下面为你讲解美化传奇NPC对话框添加图片显示实列 我们要添加你要放入npc图片的补丁. ...

  9. STM32L476RG_中断开发与实列

    本程序的主要功能是实现按键控制灯的亮灭.当灯为灭的状态时按键按下点亮灯,当灯为亮的状态时按键按下熄灭灯,即实现灯的电平翻转操作. 按键扫描是利用 GPIO 下降中断,来监测按键按下动作.并加以消抖操作 ...

随机推荐

  1. javascript高级程序设计 读书笔记2

    第五章 引用类型 对象是引用类型的实例,引用类型是一种数据结构,将数据和功能组织在一起.描述的是一类对象所具有的属性和方法.对象是某个特定引用类型的实例,新对象是使用new操作符后跟一个构造函数俩创建 ...

  2. HTML 学习笔记 JavaScript(事件)

    事件流: 事件流: 描述的是从页面中接收事件的顺序 也可以理解为事件在页面中传播的顺序: 事件: 就是用户或浏览器自身执行的某种动作 例如 click(点击) load(加载) mouseover(鼠 ...

  3. HTML 学习笔记 CSS样式(链接)

    我们能够以不同的方法为链接设置样式. 设置链接的样式 能够设置链接样式的 CSS 属性有很多种(例如 color, font-family, background 等等).链接的特殊性在于能够根据它们 ...

  4. 未能正确加载包“Microsoft.Data.Entity.Design.Package.MicrosoftDataEntityDesignPackage

    本文出处:http://blog.sina.com.cn/s/blog_6fe3efa301016i64.html vs 2005 ,vs 2008, vs 2010,安装后有时出现这个错误(我的机器 ...

  5. office 2010 2013卸载工具

    http://www.ithome.com/html/soft/32777.htm Office 2003 || Office 2007 || Office 2010.

  6. linux传输大文件

    http://dreamway.blog.51cto.com/1281816/1151886 linux传输大文件

  7. iptables案例手册

    Linux防火墙Iptable如何设置只允许某个ip访问80端口,只允许特定ip访问某端口 iptables常用实例备查(更新中) 9个常用iptables配置实例 案例: http://www.cn ...

  8. 在线文档预览方案-office web apps

    最近在做项目时,要在手机端实现在线文档预览的功能.于是百度了一下实现方案,大致是将文档转换成pdf,然后在通过插件实现预览.这些方案没有具体实现代码,也没有在线预览的地址,再加上项目时间紧迫.只能考虑 ...

  9. HoloLens开发手记 - Unity development overview 使用Unity开发概述

    Unity Technical Preview for HoloLens最新发行版为:Beta 24,发布于 09/07/2016 开始使用Unity开发HoloLens应用之前,确保你已经安装好了必 ...

  10. Google 面试

    坚持完成这套学习手册,你就可以去 Google 面试了 系统 指针 value Google 面试 阅读10266   本文为掘金投稿,译文出自:掘金翻译计划 原文地址:Google Intervie ...