是要MINA的socket开发

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 *   Socket客户端
 * 
 * 
 */
public class MinaSocketClient {
	private ConnectFuture connect;
	private IoSession session;

	public ConnectFuture getConnect() {
		return connect;
	}

	public void setConnect(ConnectFuture connect) {
		this.connect = connect;
	}

	public IoSession getSession() {
		return session;
	}

	public void setSession(IoSession session) {
		this.session = session;
	}

	public MinaSocketClient(final String serverHost, final int serverPort) {
		final IoConnector connector = new NioSocketConnector(Runtime.getRuntime().availableProcessors() + 1);
		connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
		connector.setConnectTimeoutMillis(30000);   
		connector.getFilterChain().addLast("reconnect", new IoFilterAdapter() {
			/**
			 * 检测到连接断开后自动重连
			 * session关闭,清理map
			 */
			@Override
			public void sessionClosed(NextFilter nextFilter, IoSession session)throws Exception {
				System.out.println(session + " closed.");
				MinaSocketClient.this.session = keepConnect(serverHost, serverPort,connector);
			}
		});

		connector.setHandler(new MinaSocketClientHandler());//设置事件处理器   
		keepConnect(serverHost, serverPort, connector);
	}

	/**
	 * 保持持续连接
	 * 
	 * @param serverHost
	 * @param serverPort
	 * @param connector
	 * @return
	 */
	private IoSession keepConnect(String serverHost, int serverPort,IoConnector connector) {
		while (true) {
			try {
				connect = connector.connect(new InetSocketAddress(serverHost,serverPort));
				connect.awaitUninterruptibly();
				session = connect.getSession();
				if (session.isConnected()) {
					return session;
				}
			} catch (Exception ex) {
				System.out.println("连接服务器[" + serverHost + ":" + serverPort+ "]异常,10秒后自动重试...");
				try {
					Thread.sleep(10000);
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}
			}
		}
	}
}


import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/** 
 * Socket客户端处理器
 * 
 */
public class MinaSocketClientHandler implements IoHandler{

	@Override
	public void exceptionCaught(IoSession session, Throwable arg1)
			throws Exception {
		
	}

	@Override
	public void inputClosed(IoSession session) throws Exception {
	}

	/** 
	 * 客户端接收消息
	 * 2016-1-15 下午6:01:09 
	 * @param session
	 * @param message
	 * @throws Exception 
	 */
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		 if (session == null) {
				return;
		}
		if (message != null) {
			System.out.println("接收消息:"+message);
		}
		
	}

	/** 
	 * 客户端发送消息
	 * 2016-1-15 下午6:01:19 
	 * @param session
	 * @param message
	 * @throws Exception 
	 */
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		System.out.println(session + " messageSent: " + message);
		
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		 System.out.println(session + " closed.");//session关闭
		 
		
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println(session + " connected.");//session创建
		
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus arg1) throws Exception {
		System.out.println(session + " sessionIdle.");//session创建
	}

	/** 
	 * 2016-1-18 下午5:36:03 
	 * @param session
	 * @throws Exception 
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println(session + " sessionOpened.");
	}

}



##################################################
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 *  socket服务端
 * 
 */
public class MinaSocketServer  {
	private static final Logger logger = Logger.getLogger(MinaSocketServer.class);

	/**
	 * nio-Acceptor
	 */
	private IoAcceptor acceptor;

	/**
	 * socket地址
	 */
	private List<SocketAddress> socketServerAddress = new ArrayList<SocketAddress>();

	public MinaSocketServer(String serverHost, int serverPort) {
		this.socketServerAddress.add(new InetSocketAddress(serverHost,serverPort));
	}

	/** 
	 * 创建服务端启动服务监听连接
	 * 2016-1-9 下午3:52:48 
	 * @return 
	 */
	public IoAcceptor connect() {
		acceptor = new NioSocketAcceptor();
		//解码器 -最好客户端需和服务端编码工厂一致(PrefixedStringCodecFactory)
		acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
		acceptor.getFilterChain().addLast("threadPool",new ExecutorFilter(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() + 1)));//线程池(cpu核数+1 最优设置)
		acceptor.setHandler(new MinaSocketServerHandler());//设置事件处理器   IbmsSocketServerHandler
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); //读写都空闲时间:10秒  
		try {
			acceptor.bind(this.socketServerAddress);
		} catch (Exception e) {
			logger.info(e);
			return null;
		}
		return acceptor;
	}

	/** 
	 * 关闭服务
	 * 2016-1-9 下午3:53:19  
	 */
	public void disconnect() {
		if (this.acceptor != null) {
			try {
				this.acceptor.unbind();
				this.acceptor.getFilterChain().clear();  // 清空Filter chain,防止下次重新启动时出现重名错误  
				this.acceptor.dispose();
				this.acceptor=null;
			} catch (Exception ex) {
				logger.info(ex);
			}
		}
	}
}



import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketSessionConfig;

/**
 *    Socket服务端处理器
 * 
 */
public class MinaSocketServerHandler implements IoHandler {
	private static final Logger logger = Logger.getLogger(MinaSocketServerHandler.class);

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.info(session + " exceptionCaught." + cause.getMessage());
	}

	@Override
	public void inputClosed(IoSession session) throws Exception {
		logger.info(session + " inputClosed.");
	}

	/**
	 * 接收消息
	 * 
	 * @param arg0
	 * @param arg1
	 * @throws Exception
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if (session == null) {
			return;
		}
		if (message != null) {
			System.out.println("接收的消息:"+message.toString());
		}

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.info(session + " [messageSent]: " + message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("#" + MinaSocketServerHandler.class.getName()+ ">>IoSession  关闭  "+  session + " closed.");

	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		SocketSessionConfig cfg = (SocketSessionConfig) session.getConfig();
		cfg.setKeepAlive(true);
		logger.info(session + " connected.");

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus arg1)
			throws Exception {
		logger.info(session + " sessionIdle.");

	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info(session + " sessionOpened.");

	}

}

你可能感兴趣的:(是要MINA的socket开发)