第一步:创建ArenaSessionHandle
package com.war.socket.arena;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.json.JSONObject;
import com.war.constant.ArenaSocketConstant;
public class ArenaSessionHandle extends IoHandlerAdapter{
@Override
public void sessionCreated(IoSession session) throws Exception {
}
@Override
public void sessionOpened(IoSession session) throws Exception {
}
@Override
public void sessionClosed(IoSession session) throws Exception {
session.close();
ArenaSocketService.removeArenaBattleSession(session);
}
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
session.close();
ArenaSocketService.removeArenaBattleSession(session);
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
// 处理业务逻辑
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
}
}
第二步:创建服务端 ArenaSocketServer
package com.war.socket.arena;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import com.war.common.ResourceBundleService;
public class ArenaSocketServer {
private final static int PORT = 12345;
final IoAcceptor acceptor = new NioSocketAcceptor();
private static Logger logger = Logger.getLogger(ArenaSocketServer.class);
public ArenaSocketServer() {
// 注册
acceptor.setHandler(new ArenaSessionHandle());
// 过滤器
acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
try {
// 端口绑定
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Arena Socket Server Started...");
} catch (IOException e) {
logger.error(ResourceBundleService.getString("txt.exception"), e);
}
}
public void shutdown() {
acceptor.unbind();
acceptor.dispose();
}
}