spring与mina集成可以让WEB用户在线聊天,现在网上的在线与我联系,是客户与后台的人员之间的互动;下面简单的将spring与mina集成的代码分享下:这里只能做在线的互动,但如果有一方不在线的话,需要将信息放到持久成去,等另一方上线后,再将信息发出去,所以后台还需要一个守侯线程来判断当用户上线后,是否有信息需要发送到该用户等;
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
<!-- This makes it possible to specify java.net.SocketAddress values (e.g.
:80 below) as Strings. They will be converted into java.net.InetSocketAddress
objects by Spring. -->
<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>
<!-- The IoHandler implementation -->
<bean id="myHandler" class="com.cigna.cmc.spring.socket.Server.MinaProtocolHandler" />
//executorFilter多线程处理
<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>
//处理对象流时候用ObjectSerializationCodecFactory
<bean id="codecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
<constructor-arg>
<bean
class="org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory" />
</constructor-arg>
</bean>
<bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />
<!-- The IoAcceptor which binds to port 1235 server side -->
<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="myHandler" />
<property name="reuseAddress" value="true" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>
</beans>
服务端的处理:
public class MinaProtocolHandler extends IoHandlerAdapter {
private final Logger logger = LoggerFactory
.getLogger(MinaProtocolHandler.class);
private final Set<IoSession> sessions = Collections
.synchronizedSet(new HashSet<IoSession>());
public void sessionCreated(IoSession session) throws Exception {
// session.write("direct come from server......");
sessions.add(session);
}
// 当接收到客户端的请求信息后触发此方法.
public void messageReceived(IoSession session, Object message) {
if (message instanceof EntityTest) {
if (session.getAttribute(((EntityTest) message).getUserName()) == null) {
session.setAttribute(((EntityTest) message).getUserName(),
message);
sessions.add(session);
}
}
System.out.println("session.getAttribute(userName) messageReceived"
+ session.getAttribute("userName"));
System.out.println(((InetSocketAddress) session.getRemoteAddress())
.getAddress().getHostAddress());
System.out.println(message);
System.out.println(((EntityTest) message).getUserName());
System.out.println(((EntityTest) message).getHostName());
Iterator<?> tempIter = sessions.iterator();
IoSession tempSession = null;
while (tempIter.hasNext()) {
tempSession = (IoSession) tempIter.next();
StringBuffer sb = new StringBuffer();
sb.append("hostName="
+ ((InetSocketAddress) tempSession.getRemoteAddress())
.getAddress()
+ "|port="
+ ((InetSocketAddress) tempSession.getRemoteAddress())
.getPort());
System.out.println(sb.toString());
if (tempSession.getAttribute(((EntityTest) message).getUserName()) != null) {
session.write("Server Send: " + message);
}
}
}
// 当信息已经传送给客户端后触发此方法.
public void messageSent(IoSession session, Object message) throws Exception {
}
public void sessionIdle(IoSession session, IdleStatus status) {
// disconnect an idle client
session.close();
}
public void sessionClosed(IoSession session) throws Exception {
sessions.remove(session);
}
public void exceptionCaught(IoSession session, Throwable cause) {
logger.warn("Unexpected exception.", cause);
session.close();
}
}
客户端调用代码:
public class 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.
EntityTest et = new EntityTest();
et.setHostName(((InetSocketAddress) session.getServiceAddress())
.getHostName());
et.setPort(((InetSocketAddress) session.getServiceAddress())
.getPort());
et.setMsg((String) message);
et.setUserName("xlp");
session.write(et);
// session.wait();
return true;
} catch (Exception e) {
return false;
}
}
public void close() {
if (session != null) {
if (session.isConnected()) {
// Wait until the chat ends.
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("localhost");
client.setPort(1235);
String msg = "hello world!";
client.send(msg);
System.out.println("Client Send: " + msg);
client.close();
}
}
客户端的处理:
class MinaClientHandler extends IoHandlerAdapter {
private static final IoFilter LOGGING_FILTER = new LoggingFilter();
// ObjectSerializationCodecFactory TextLineCodecFactory
private static final IoFilter CODEC_FILTER = new ProtocolCodecFilter(
new ObjectSerializationCodecFactory());
@Override
public void sessionCreated(IoSession session) throws Exception {
session.getFilterChain().addLast("codec", CODEC_FILTER);
session.getFilterChain().addLast("logger", LOGGING_FILTER);
// session.setAttribute("userName", "harold");
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String msg = (String) message;
System.out.println("Client Received: " + msg);
}
}