spring mina整合(客户端进行调用)

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();
 }

 

有什么疑问欢迎进行讨论,写的不深入。

爱生活,爱分享,爱康宝!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页