⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverthread.java

📁 Mina框架http协议简单实现。Mina框架效率与c程序比较接近
💻 JAVA
字号:
package com.eshore.pubservice.nio;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

import com.eshore.pubservice.nio.codec.DefaultCodecFactory;
import com.eshore.pubservice.nio.codec.ICodecFactory;
import com.eshore.pubservice.nio.codec.ProtocolCodecFactory;
import com.eshore.pubservice.nio.handle.DefaultHandlerFactory;
import com.eshore.pubservice.nio.handle.IHandlerFactory;
import com.eshore.pubservice.nio.handle.ProtocolHandlerAdapter;

/**
 * 服务启动线程.
 * 
 * @author lishuisheng
 *
 */
public class ServerThread implements Runnable {
	
	private static Logger log=Logger.getLogger(ServerThread.class);
	
	private ICodecFactory codecFactory;
	
	private IHandlerFactory handlerFactory;
	
	private Integer port;
	
	private static final int DEFAULT_PORT=8686;
	
	public ServerThread(){
		this(new DefaultCodecFactory(),new DefaultHandlerFactory());
	}
	
	public ServerThread(ICodecFactory codecFactory,IHandlerFactory handlerFactory){
		this.codecFactory=codecFactory;
		this.handlerFactory=handlerFactory;
	}
	
	public void setPort(int port){
		this.port=port;
	}
	
	public void startServer(){
		Thread t=new Thread(this);
		t.start();
	}

	public void run() {
		try{
			IoAcceptor acceptor=new SocketAcceptor();
			SocketAcceptorConfig config=new SocketAcceptorConfig();
			ProtocolCodecFactory codFactory=new ProtocolCodecFactory(codecFactory);
			ProtocolCodecFilter filter=new ProtocolCodecFilter(codFactory);
			
			config.getFilterChain().addLast("codec", filter);
			
			ProtocolHandlerAdapter handlerAdaptor=new ProtocolHandlerAdapter(handlerFactory);
			if(port==null){
				port=DEFAULT_PORT;
			}
			acceptor.bind(new InetSocketAddress(port), handlerAdaptor, config);
			log.info(".....mina nio server started...");
			log.info(".....listening at :"+port+"....");
		}catch(Exception e){
			log.debug("Server thread start faile!");
			e.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -