MINA等异步单工长通讯问题
< 返回列表时间: 2017-01-09来源:开源中国
HDC调试需求开发(15万预算),能者速来!>>>
最近接了个项目,需要用异步单工长连接,同银联方进行交互,因为对方用的就是这实现,但是我们用的是mina同步短连接,这里我试了mina的异步长短通讯、socket的通讯、netty的通讯连接,都不完美,第一个,多几笔,提示hander未关闭,第二个发过去的数据对方不认识。第三个,发过去但收不到响应。。。。,用短连接发送再加一个client端口启动接收,能发能收,但并发量和接收数据处理这块也容易混乱!求大神指导下,或者给个这种类型的demo 灰常感谢!!!
demo:
sendMsg(Object msg) throws CharacterCodingException, UnsupportedEncodingException{

NioSocketConnector connector = new NioSocketConnector();
//connector.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE,10); //写 通道均在10 秒内无任何操作就进入空闲状态
//connector.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE,10); //读 通道均在10 秒内无任何操作就进入空闲状态
connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10); //读写 通道均在10 秒内无任何操作就进入空闲状态
connector.getSessionConfig().setWriteTimeout(3000);
connector.getSessionConfig().setReadBufferSize(2048);
connector.setConnectTimeoutMillis(4000);
connector.getFilterChain().addLast("codec", CODEC_FILTER);
connector.setHandler(new MinaClientHander() );

ConnectFuture cf = connector.connect(new InetSocketAddress(IP,PORT));
cf.join();
// 等待连接成功
cf.awaitUninterruptibly();
IoSession session = cf.getSession();
System.out.println("开始发消息【"+msg+"】去通道方!!!");

if(msg.toString().length()>20){
String msgStr = "";
Charset charset =Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
if (msg instanceof byte[])
{
msgStr = new String((byte[]) msg, "ISO-8859-1");
} else
{
msgStr = msg.toString();
}
String value;
value =setMsgLength(msgStr);
IoBuffer buf = IoBuffer.allocate(value.length())
.setAutoExpand(true);
buf.putString(value, encoder);
buf.flip();
System.out.println("MsgHeadProcess 报文发送编码 【 " + new Date(System.currentTimeMillis())
+ "】 data【" +buf.getHexDump());
session.write(buf);
session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
connector.dispose();
session.close();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else{
session.write(msg);
session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
connector.dispose();
session.close();

}








static{
// 服务端的实例
NioSocketAcceptor accept = new NioSocketAcceptor();
// 添加filter
accept.getFilterChain().addLast("codec",new ProtocolCodecFilter(
new MinaEncoder(),
new MinaDecoder()
));
// 添加filter,日志信息
// accept.getFilterChain().addLast("logging", new LoggingFilter());
// 添加线程池
accept.getFilterChain().addLast("ThreadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
accept.getSessionConfig().setReadBufferSize(2048);
accept.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);

// 设置服务端的handler
accept.setHandler(new MinaServerHander());
try {
int PORT=10006;
accept.bind(new InetSocketAddress(PORT));
log.info("服务端启动!端口:"+PORT);
} catch (IOException e) {
log.error("socket listener start exception", e);
}
log.info("mina server started.");
}
热门排行