MIAN2客户端与spring的整合

项目中遇到要在Java web项目中使用mina2客户端,并且是一个常连接。尝试了将其整合到web项目中。以下是部分代码实现。
1.ProcessHandler.java

public class ProcessHandler extends IoHandlerAdapter {
private String hostName ;
//MINA2 服务器 IP 数组
private static final String[] HOSTS = {"",""};
private static final int CONNECT_TIMEOUT = 1000;
private NioSocketConnector connector;
private static final int PORT = 1234;
private IoSession session;
private ConnectFuture future;
// 构造方法
public ProcessHandler () {

   this.hostName = this.selectServer();
}
// 随机选择 MINA2 服务器 IP,以实现 MINA2 集群
private String selectServer() {
try {
int cc = HOSTS.length;
if (cc <= 0)
return null;
Random rd = new Random();
int idx = (Math.abs(rd.nextInt()) % cc);
return HOSTS[idx];
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public IoSession connect() {
if (session != null && session.isConnected()) {
return session;
}
try {
connector = new NioSocketConnector();
connector.setConnectTimeoutMillis(CONNECT_TIMEOUT );
connector.getFilterChain().addLast( "codec",
  (IoFilter) new ProtocolCodecFilter(
  new ObjectSerializationCodecFactory()));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(this);
future = connector.connect(new InetSocketAddress(hostName, PORT ));
future.awaitUninterruptibly();
if (!future.isConnected()) {
return null;
}
session = future.getSession();
} catch (Exception ex) {
throw new IllegalStateException("session is already closed");
}
return session;
}

@Override
public void sessionOpened(IoSession session) throws Exception { 
   
System.err.println("open");


@Override 
public void messageReceived(IoSession session, Object message) 
        throws Exception { 
    System.out.println("批复:" + message.toString()); 


@Override 
public void messageSent(IoSession session, Object message) throws Exception {
    System.out.println("报告:" + message.toString()); 


@Override 
public void exceptionCaught(IoSession session, Throwable cause) 
        throws Exception { 
    cause.printStackTrace(); 
    session.close(true); 
}
}

2.applicationContext.xml
<bean id="ProcessHandler" name="ProcessHandler" class="com.dong.web.utils.ProcessHandler"/>

3.ApplicationContextListener.java
@WebListener
public class ApplicationContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent servletContextEvent) {

WebApplicationContext wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(servletContextEvent
.getServletContext());
ProcessHandler handler  = (ProcessHandler) wac.getBean("ProcessHandler");
IoSession ioSession = handler.connect();
wac.getServletContext().setAttribute("iosession", ioSession);

}

public void contextDestroyed(ServletContextEvent event) {
event.getServletContext().setAttribute("iosession", null);
}
4.使用时只要从ServletContext中获取iosession,便可以向minaServer发送数据。

你可能感兴趣的:(Mina)