spring mina整合(客戶端進行呼叫)

康_寶發表於2014-06-18

1.需要的包

mina-core-2.0.4.jar
mina-integration-beans-2.0.4.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.web-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
commons-logging-1.1.jar
org.springframework.asm-3.0.5.RELEASE.jar
org.springframework.expression-3.0.5.RELEASE.jar
slf4j-log4j12-1.5.8.jar
slf4j-api-1.5.8.jar
log4j-1.2.14.jar

2.新建SpringMina web 專案,先看下我的目錄:

3.在web.xml中配置如下資訊:

<context-param>
   <param-name>contextConfigLocation</param-name>
    <!-- 上面配置的spring配置檔案的路徑,區分大小寫 -->
    <param-value>
     classpath:/config/spring/applicationContext-mina.xml
    </param-value>
   </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 <!-- Character Encoding filter -->
 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 
 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

4.新建Source folder名為config,新建包名為config.spring,在此報下面建applicationContext-mina.xml檔案,內容如下(標頭檔案要加上):

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
   <map>
    <entry key="java.net.SocketAddress">
     <bean class="org.apache.mina.integration.beans.InetSocketAddressEditor" />
    </entry>
   </map>
  </property>
 </bean>
 
 <!-- 服務端處理 -->
 <bean id="minaHandler" class="com.sk.mina.MinaProtocolHandler" />
 
 <!-- the IoFilters -->
 <bean id="executorFilter" class="org.apache.mina.filter.executor.ExecutorFilter" />
 
 <bean id="mdcInjectionFilter" class="org.apache.mina.filter.logging.MdcInjectionFilter">
  <constructor-arg value="remoteAddress" />
 </bean>
 
 <bean id="codecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
  <constructor-arg>
   <bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory" />
  </constructor-arg>
 </bean>
 
 <bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />
 
 <!-- The non-SSL filter chain. -->
 <bean id="filterChainBuilder"
  class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
  <property name="filters">
   <map>
    <entry key="executor" value-ref="executorFilter" />
    <entry key="mdcInjectionFilter" value-ref="mdcInjectionFilter" />
    <entry key="codecFilter" value-ref="codecFilter" />
    <entry key="loggingFilter" value-ref="loggingFilter" />
   </map>
  </property>
 </bean>
 
 <!-- The IoAcceptor which binds to port 1235 server side -->
 <bean id="minaAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
  init-method="bind" destroy-method="unbind">
  <property name="defaultLocalAddress" value=":1235" />
  <property name="handler" ref="minaHandler" />
  <property name="reuseAddress" value="true" />
  <property name="filterChainBuilder" ref="filterChainBuilder" />
 </bean>

6.新建包名com.sk.mina,新建MinaProtocolHandler類(服務端應用程式),並且繼承IoHandlerAdapter類,內容如下:

private final Logger logger = LoggerFactory.getLogger(getClass());

 public void messageReceived(IoSession session, Object message) {
  String msg = (String) message;
  System.out.println("Server Received: " + msg);
  session.write("Server Send: " + msg);
  //sessions.add(session);
 }

 @SuppressWarnings("deprecation")
 public void sessionIdle(IoSession session, IdleStatus status) {
  //disconnect an idle client
  session.close();
 }

 @SuppressWarnings("deprecation")
 public void exceptionCaught(IoSession session, Throwable cause) {
  logger.warn("Unexpected exception.", cause);
  session.close();
 }

7.新建MinaClientHandler類(用來處理服務端發過來的資訊),並繼承IoHandlerAdapter類,內容如下:

private static final IoFilter LOGGING_FILTER = new LoggingFilter();

 private static final IoFilter CODEC_FILTER = new ProtocolCodecFilter(
   new TextLineCodecFactory());

 @Override
 public void sessionCreated(IoSession session) throws Exception {
  session.getFilterChain().addLast("codec", CODEC_FILTER);
  session.getFilterChain().addLast("logger", LOGGING_FILTER);
 }

 @Override
 public void messageReceived(IoSession session, Object message)
   throws Exception {
  String msg = (String) message;
  System.out.println("Client Received: " + msg);
 }

8.新建MinaClientSupport類(負責傳送客戶端的請求到伺服器端),內容如下:

private IoHandler handler = null;

 private IoSession session;

 private String host;

 private int port;

 public boolean send(Object message) {
  if (session != null && session.isConnected()) {
   throw new IllegalStateException(
     "Already connected. Disconnect first.");
  }
  SocketAddress address = new InetSocketAddress(host, port);
  NioSocketConnector connector = new NioSocketConnector();
  try {

   connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());

   connector.setHandler(handler);
   ConnectFuture future1 = connector.connect(address);
   future1.awaitUninterruptibly();
   if (!future1.isConnected()) {
    return false;
   }
   session = future1.getSession();
   session.write(message);
   return true;
  } catch (Exception e) {
   return false;
  }
 }

 @SuppressWarnings("deprecation")
 public void close() {
  if (session != null) {
   if (session.isConnected()) {
    session.getCloseFuture().awaitUninterruptibly();
   }
   session.close();
  }
 }

 public String getHost() {
  return host;
 }

 public void setHost(String host) {
  this.host = host;
 }

 public int getPort() {
  return port;
 }

 public void setPort(int port) {
  this.port = port;
 }

 public void setHandler(IoHandler handler) {
  this.handler = handler;
 }

 public static void main(String[] args) {
  System.out.println("---------------------");
  MinaClientSupport client = new MinaClientSupport();
  MinaClientHandler handler = new MinaClientHandler();
  client.setHandler(handler);
  client.setHost("127.0.0.1");
  client.setPort(1235);
  String msg = "hello world!";
  client.send(msg);
  System.out.println("Client Send: " + msg);
  client.close();
 }

 

有什麼疑問歡迎進行討論,寫的不深入。

愛生活,愛分享,愛康寶!

相關文章