<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    sblig

    BlogJava 首頁 新隨筆 聯系 聚合 管理
      10 Posts :: 0 Stories :: 0 Comments :: 0 Trackbacks

    2012年9月28日 #

    最后 遺留一個問題,繼續探索中....

    ?

    ?

    跟我學Spring3 學習筆記一

    跟我學Spring3 學習筆記二

    跟我學Spring3 學習筆記三

    跟我學Spring3 學習筆記四

    跟我學Spring3 學習筆記五 注入

    跟我學Spring3 學習筆記六 注入

    ?

    統一接口:

    ?

    public interface HelloApi {
    	public void sayHello();  
    }
    

    ?

    ?

    一、延遲初始化:

    ?

    /**
     * 延遲初始化Bean
     *     延遲初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用時才創建及初始化Bean。
     *     配置方式很簡單只需在<bean>標簽上指定 “lazy-init” 屬性值為“true”即可延遲初始化Bean。
     */
    public class DiLazyInit implements HelloApi{
    
    	public void sayHello() {
    		System.out.println("say DiInitDestory");
    	}
    	
    	public DiLazyInit(){
    		System.out.println("初始化 DiInitDestory");
    	}
    }

    ?

    ?

    配置延遲初始化:

    ?

    ?

    <!-- 延遲初始化Bean 
    	     延遲初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用時才創建及初始化Bean。
    	     配置方式很簡單只需在<bean>標簽上指定 “lazy-init” 屬性值為“true”即可延遲初始化Bean。 -->
    	<bean id="lazyinitDi" class="com.diinit.DiLazyInit"
    		lazy-init="true">
    	</bean>

    ?

    ?junit 進行測試:

    ?

    @Test
    	public void testLazyInit(){
    		ApplicationContext context = new ClassPathXmlApplicationContext("initdepends.xml");
    		HelloApi lazyInit = context.getBean("lazyinitDi",HelloApi.class);
    		lazyInit.sayHello();
    		System.out.println("");
    	}
    ?

    ?

    注意這個時候的輸出結果:

    ?

    ?

    初始化 DiLazyInit

    say DiLazyInit

    ?

    ?

    ?

    ?

    二、 可以指定初始化和銷毀的順序

    ?

    ?

    /* 使用depends-on 是指 指定Bean初始化及銷毀時的順序,使用depends-on屬性指定的Bean要先初始化完畢
    *     后才初始化當前Bean,由于只有“singleton”Bean能被Spring管理銷毀,所以當指定的Bean都是“singleton”
    *     時,使用depends-on屬性指定的Bean要在指定的Bean之后銷毀。
    *     “decorator”指定了“depends-on”屬性為“lazyinitDi”,所以在“decorator”Bean初始化之前要先初
    *     始化“lazyinitDi”,而在銷毀“lazyinitDi”之前先要銷毀“decorator”,大家注意一下銷毀順序,與文檔上的不符。
    *     “depends-on”屬性可以指定多個Bean,若指定多個Bean可以用“;”、“,”、空格分割。
    *     
    *  那“depends-on”有什么好處呢?
    *     主要是給出明確的初始化及銷毀順序,比如要初始化“decorator”時要確保“lazyinitDi”Bean的資源準備好了,
    *     否則使用“decorator”時會看不到準備的資源;而在銷毀時要先在“decorator”Bean的把對“helloApi”資源的引用釋
    *     放掉才能銷毀“lazyinitDi”,否則可能銷毀 “lazyinitDi”時而“decorator”還保持著資源訪問,造成資源不能釋放或釋放錯誤。
    */
    public class ApiDecorator implements HelloApi{
    
    	private HelloApi helloApi;
    	
    	public ApiDecorator(){
    		System.out.println("初始化 ApiDecorator");
    	}
    	
    	public void sayHello() {
    		System.out.println("say ApiDecorator");
    		helloApi.sayHello();
    		
    	}
    
    	public HelloApi getHelloApi() {
    		return helloApi;
    	}
    
    	public void setHelloApi(HelloApi helloApi) {
    		this.helloApi = helloApi;
    	}
    }
    ?

    ?

    配置xml指定初始化和銷毀順序:

    ?

    <!-- 初始化及銷毀時的順序    
    	     “decorator”指定了“depends-on”屬性為“lazyinitDi”,所以在“decorator”Bean初始化之前
    	     要先初始化“lazyinitDi”,而在銷毀“lazyinitDi”之前先要銷毀“decorator”,大家注意一下銷毀順序 -->
    	<bean id="decorator" class="com.diinit.ApiDecorator"
    		depends-on="lazyinitDi">
    		<property name="helloApi">
    			<ref bean="lazyinitDi" />
    		</property>
    	</bean>
    ?

    ?

    ?

    ?junit 進行測試:

    ?

    @Test
    	public void testLazyInit(){
    		ApplicationContext context = new ClassPathXmlApplicationContext("initdepends.xml");
    		HelloApi lazyInit = context.getBean("lazyinitDi",HelloApi.class);
    		lazyInit.sayHello();
    		System.out.println("");
    	}
    	
    	@Test
    	public void testDependsOn(){
    		ApplicationContext context= new ClassPathXmlApplicationContext("initdepends.xml");
    		HelloApi depends = context.getBean("decorator",HelloApi.class);
    		depends.sayHello();
    	}
    ?

    ?

    注意這個時候的輸出結果:

    ?

    ?

    初始化 DiLazyInit

    初始化 ApiDecorator ? ? ? ? ? ?//也是上面同樣的測試函數 testLazyInit(),同樣的配置 ?這句是多打印出來的

    say DiLazyInit

    ?

    初始化 DiLazyInit

    初始化 ApiDecorator

    say ApiDecorator

    say DiLazyInit


    ?

    ?

    ?

    這突然多出來的打印結果,說明進行了ApiDecorator的對象的創建,

    但是在第一個配置中也沒涉及到?ApiDecorator 類的加載,注入 ?。

    ?

    什么原因造成的呢?是一種隱藏的注入? 繼續探索中....

    ?

    ?



    已有 1 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-10-18 16:45 李凡 閱讀(164) | 評論 (0)編輯 收藏


    跟我學Spring3 學習筆記一

    跟我學Spring3 學習筆記二

    跟我學Spring3 學習筆記三

    跟我學Spring3 學習筆記四

    跟我學Spring3 學習筆記五 注入

    ?

    ?

    引用其它Bean

    ?

    一、構造器注入方式:

    (1)通過” <constructor-arg>”標簽的ref屬性來引用其他Bean

    ?

    (2)通過” <constructor-arg>”標簽的子<ref>標簽來引用其他Bean,使用bean屬性來指定引用的Bean

    二、setter注入方式:

    (1)通過” <property>”標簽的ref屬性來引用其他Bean

    (2)通過” <property>”標簽的子<ref>標簽來引用其他Bean,使用bean屬性來指定引用的Bean

    ?

    ?

    public class HelloDiBean implements HelloApi{
    
    	private HelloApi helloApi;
    	private HelloApi helloApi2;
    	
    
    	public HelloDiBean(HelloApi helloApi){
    		this.helloApi = helloApi;
    	}
    	
    	public void sayHello() {
    		helloApi.sayHello();
    		helloApi2.sayHello();
    	}
    	
    
    	public HelloApi getHelloApi2() {
    		return helloApi2;
    	}
    
    	public void setHelloApi2(HelloApi helloApi2) {
    		this.helloApi2 = helloApi2;
    	}
    }
    

    ?配置注入引用其他的bean

    ?

    <!-- 引用其他的bean進行注入 -->
    	<bean id="helloBean" class="com.dilist.HelloDiBean">
    		<constructor-arg index="0" ref="mapBean" />
    		<property name="helloApi2">
    			<ref bean="properBean" />
    		</property>
    	</bean>
    	
    ?

    其他引用bean 的高級用法:

    ?

    /**
     * Spring還提供了另外兩種更高級的配置方式,<ref local=””/>和<ref parent=””/>:
     * (1)<ref local=””/>配置方式:用于引用通過<bean id=”beanName”>方式中通過id屬性指定的Bean,
     * 		它能利用XML解析器的驗證功能在讀取配置文件時來驗證引用的Bean是否存在。
     * 		因此如果在當前配置文件中有相互引用的Bean可以采用<ref local>方式從而如果配置錯誤能在開發調試時就發現錯誤。
     * (2)<ref parent=””/>配置方式:用于引用父容器中的Bean,不會引用當前容器中的Bean,
     *       當然父容器中的Bean和當前容器的Bean是可以重名的,獲取順序是直接到父容器找。
     */
    public class HelloHigh implements HelloApi{
    	
    	private HelloApi helloApi;
    	private HelloApi helloApi2;
    	
    
    	public HelloHigh(HelloApi helloApi){
    		this.helloApi = helloApi;
    	}
    	
    	public void sayHello() {
    		helloApi.sayHello();
    		System.out.println("");
    		helloApi2.sayHello();
    	}
    	
    
    	public HelloApi getHelloApi2() {
    		return helloApi2;
    	}
    
    	public void setHelloApi2(HelloApi helloApi2) {
    		this.helloApi2 = helloApi2;
    	}
    
    }
    ?

    helloworld.xml:

    ?

    <!-- 注入properties類型 -->
    	<bean id="properBean" class="com.dilist.HelloDiProperties">
    		<property name="properties">
    			<props value-type="int" merge="default"><!-- 雖然指定value-type,但是不起作用 -->
    				<prop key="1">1sss</prop>           <!-- Properties 建和值都是String類型 -->
    				<prop key="2">2</prop>
    			</props>
    		</property>
    		<property name="properties2">
    			<value> <!-- 分隔符可以是 “換行”、“;”、“,” 不建議該方式,優先選擇第一種方式 -->
    				1=11
    				2=22;<!-- 這樣的分隔符好像沒用 -->
    			    3=33,
    				4=44
    			</value>
    		</property>
    	</bean>
    
    	<!-- Spring還提供了另外兩種更高級的配置方式,<ref local=””/>和<ref parent=””/> -->
    	<bean id="helloHigh" class="com.dilist.HelloHigh">
    		<constructor-arg index="0"><ref local="properBean" /></constructor-arg>
    		<property name="helloApi2"><ref parent="properBean" /></property>	
    	</bean>
    ?

    ?

    helloworldParent.xml:

    ?

    <!-- 注入properties類型 -->
    	<bean id="properBean" class="com.dilist.HelloDiProperties">
    		<property name="properties">
    			<props value-type="int" merge="default"><!-- 雖然指定value-type,但是不起作用 -->
    				<prop key="1">2dss</prop>           <!-- Properties 建和值都是String類型 -->
    				<prop key="2">3aas</prop>
    			</props>
    		</property>
    		<property name="properties2">
    			<value> <!-- 分隔符可以是 “換行”、“;”、“,” 不建議該方式,優先選擇第一種方式 -->
    				1=111
    				2=222;<!-- 這樣的分隔符好像沒用 -->
    			    3=333,
    				4=444
    			</value>
    		</property>
    	</bean>
    ?

    調用處 利用加載父容器的方式,注入父容器中的Bean:

    ?

    ?

    @Test
    	public void testDiBeanHigh() {
    		// 以classes為根目錄算起
    		// 讀取配置文件實例化一個Ioc容器
    
    		// 初始化父容器
    		ApplicationContext parentContext = new ClassPathXmlApplicationContext(
    				"helloworldParent.xml");
    
    		// 初始化當前容器
    		ApplicationContext context = new ClassPathXmlApplicationContext(
    				new String[] { "helloworld.xml" }, parentContext);
    
    		// 構造 + setter注入 引用其他的bean注入
    		HelloApi helloApi = context.getBean("helloHigh", HelloApi.class);
    		helloApi.sayHello();
    
    	}


    已有 0 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-10-18 14:32 李凡 閱讀(147) | 評論 (0)編輯 收藏



    已有 1 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-10-17 16:14 李凡 閱讀(125) | 評論 (0)編輯 收藏

    ASM 進行動態生成class
    import org.objectweb.asm.ClassWriter;
    import org.objectweb.asm.MethodVisitor;
    import org.objectweb.asm.Opcodes;
    
    public class HelloWorld extends ClassLoader implements Opcodes{
    	public static void main(String[] args) {
    		ClassWriter cw = new ClassWriter(0);
    		cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
    		MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    		mw.visitVarInsn(ALOAD, 0);
    		mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    		mw.visitInsn(RETURN);
    		mw.visitMaxs(1, 1);
    		mw.visitEnd();
    		
    		mw = cw.visitMethod(ACC_PUBLIC+ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
    		mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    		mw.visitLdcInsn("Hello World!");
    		mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
    		mw.visitInsn(RETURN);
    		mw.visitMaxs(2, 2);
    		mw.visitEnd(); 
    		
    		byte[] code = cw.toByteArray();
    		FileOutputStream fos;
    		try {
    			fos = new FileOutputStream("Example.class");
    			fos.write(code);
    			fos.close();
    			
    			HelloWorld loader = new HelloWorld();   
    		     Class exampleClass = loader   
    		         .defineClass("Example", code, 0, code.length);  
    				exampleClass.getMethods()[0].invoke(null, new Object[] { null });
    				
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		
    	}
    }

    ?

    cglib 動態生成class 并進行攔截

    ?

    public class MyClass {
    	public void print() {
    		System.out.println("I'm in MyClass.print!");
    	}
    }
    
    
    import net.sf.cglib.proxy.Callback;
    import net.sf.cglib.proxy.Enhancer;
    import net.sf.cglib.proxy.MethodInterceptor;
    import net.sf.cglib.proxy.MethodProxy;
    
    public class Main {
    
    	public static void main(String[] args) {
    
    		Enhancer enhancer = new Enhancer();
    		enhancer.setSuperclass(MyClass.class);
    		enhancer.setCallback((Callback) new MethodInterceptorImpl());
    		MyClass my = (MyClass) enhancer.create();
    		my.print();
    	}
    
    	private static class MethodInterceptorImpl implements MethodInterceptor {
    
    		public Object intercept(Object obj, Method method, Object[] args,
    				MethodProxy proxy) throws Throwable {
    			// log something
    			System.out.println(method + " intercepted!");
    
    			proxy.invokeSuper(obj, args);
    			return null;
    		}
    
    	}
    }
    ?

    已有 1 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-10-16 11:18 李凡 閱讀(152) | 評論 (0)編輯 收藏

    工具類:

    ?

    ?

    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.RandomAccessFile;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;
    
    import sun.net.TelnetInputStream;
    import sun.net.TelnetOutputStream;
    import sun.net.ftp.FtpClient;
    import sun.net.ftp.FtpLoginException;
    
    public class FtpUtil {
    
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		FtpUtil ftp = new FtpUtil();
    		ftp.connect("10.16.12.75", 21, "ftpusr", "ftpusr");
    		try {
    			// 上傳目錄下文件 并可以遞歸到子目錄
    			// ftp.upPathFile(new File("D:\\ALSC"), "ALSC/");
    			// 下載目錄下多個文件 并可以遞歸到子目錄
    			//ftp.downPathFile("/opt/ftp/outgoing/cs/", "D:/outgoing/csvc");
    			
    			// 切換目錄
    			ftp.setPath("/opt/ftp/book");
    			System.out.println(ftp.getDir());
    			for (String file : ftp.getFileNameList()) {
    				System.out.println(file);
    			}
    
    			// 切換到父級目錄
    			ftp.up();
    			
    			// 創建多目錄
    			// ftp.createDir("aa/bb/cc");
    			ftp.setPath("ftpTest");
    			
    			// 刪除文件
    			ftp.deleteFile("bbb.bmp");
    			System.out.println(ftp.getDir());
    			for (String file : ftp.getFileNameList()) {
    				System.out.println(file);
    			}
    			// 上傳 下載單個文件
    			ftp.uploadFile("c:/aaa.bmp", "bbb.bmp");
    			ftp.downloadFile("bbb.bmp", "c:/bbb");
    
    			List<String> list = ftp.getFileList();
    			for (String file : list) {
    				System.out.println(file);
    			}
    
    			ftp.setPath("/opt/ftp/outgoing/cs");
    			String patternStr = "^CSGET_[0-9]{4}_0085_"+"20120926"+"_[0-9]{3}";
    			// 過濾,獲取目錄下的文件列表
    			list = ftp.getFileList(new CSFilter(patternStr));
    			for (String file : list) {
    				System.out.println(file);
    			}
    			
    			//下載 過濾后的文件
    			ftp.downPathFile("/opt/ftp/outgoing/cs/", "D:/outgoing/csvc",new CSFilter(patternStr));
    
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
    		ftp.close();
    	}
    	
    	private FtpClient ftpClient = null;
    
    	/**
    	 * 打開連接
    	 * 
    	 * @param hostname
    	 * @param port
    	 * @param username
    	 * @param passwd
    	 * @return
    	 */
    	public void connect(String hostname, int port, String username,
    			String passwd) {
    		String msg = "";
    		try {
    			ftpClient = new FtpClient(hostname, port);
    			ftpClient.login(username, passwd);
    			ftpClient.binary();
    			msg = "連接成功!";
    		} catch (FtpLoginException e) {
    			msg = "登錄主機失敗,可能是用戶名密碼錯誤!";
    			e.printStackTrace();
    		} catch (IOException e) {
    			msg = "登錄主機失敗,請檢驗端品是否正確!";
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			msg = "無權連接主機,主確認是否有權限連接主機!";
    			e.printStackTrace();
    		}
    		System.out.println(msg);
    	}
    
    	/**
    	 * 關閉連接
    	 */
    	public void close() {
    		if (ftpClient == null) {
    			return;
    		}
    		try {
    			ftpClient.closeServer();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 重命名
    	 * 
    	 * @param oldName
    	 * @param newName
    	 * @return
    	 */
    	public boolean renameFile(String oldName, String newName) {
    		boolean result = false;
    		try {
    			this.ftpClient.rename(oldName, newName);
    			result = true;
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    
    	/**
    	 * 取得相對于當前連接目錄的某個目錄下所有文件列表
    	 * 
    	 * @param path
    	 * @return
    	 */
    	public List getFileList(String path) {
    		List list = new ArrayList();
    		DataInputStream dis;
    		try {
    			dis = new DataInputStream(ftpClient.nameList(this.getDir() + path));
    			String filename = "";
    			while ((filename = dis.readLine()) != null) {
    				list.add(filename);
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return list;
    	}
    
    	/**
    	 * 讀取文件列表
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public List<String> getFileList() throws IOException {
    		List<String> fileList = new ArrayList<String>();
    		InputStreamReader isr = null;
    		BufferedReader br = null;
    		try {
    			isr = new InputStreamReader(this.ftpClient.list());
    			br = new BufferedReader(isr);
    			String fileName = "";
    			while (true) {
    				fileName = br.readLine();
    				if (fileName == null) {
    					break;
    				}
    				fileList.add(fileName);
    			}
    		} finally {
    			if (br != null) {
    				try {
    					br.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (isr != null) {
    				try {
    					isr.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return fileList;
    	}
    
    	/**
    	 * 讀取文件列表
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public List<String> getFileList(FileFilter filter) throws IOException {
    		List<String> fileList = new ArrayList<String>();
    		InputStreamReader isr = null;
    		BufferedReader br = null;
    		try {
    			isr = new InputStreamReader(this.ftpClient.list());
    			br = new BufferedReader(isr);
    			String fileName = "";
    			while (true) {
    				fileName = br.readLine();
    				if (fileName == null) {
    					break;
    				}
    				if ((filter == null) || filter.accept(new File(fileName)))
    					fileList.add(fileName);
    			}
    		} finally {
    			if (br != null) {
    				try {
    					br.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (isr != null) {
    				try {
    					isr.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return fileList;
    	}
    
    	/**
    	 * 獲取文件名列表
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public List<String> getFileNameList() throws IOException {
    		List<String> fileNameList = new ArrayList<String>();
    		InputStreamReader isr = null;
    		BufferedReader br = null;
    		try {
    			isr = new InputStreamReader(this.ftpClient.nameList(this.getDir()));
    			br = new BufferedReader(isr);
    
    			String fileName = "";
    			while (true) {
    				fileName = br.readLine();
    				if (fileName == null) {
    					break;
    				}
    				fileNameList.add(fileName);
    			}
    		} finally {
    			if (br != null) {
    				try {
    					br.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (isr != null) {
    				try {
    					isr.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return fileNameList;
    
    	}
    
    	/**
    	 * 設置路徑 切換目錄
    	 * 
    	 * @param path
    	 * @return
    	 */
    	public boolean setPath(String path) {
    		if (this.ftpClient != null) {
    			try {
    				ftpClient.cd(path);
    				return true;
    			} catch (IOException e) {
    				e.printStackTrace();
    				return false;
    			}
    		} else {
    			return false;
    		}
    	}
    
    	/**
    	 * 判斷是否為目錄
    	 * 
    	 * @param line
    	 * @return
    	 */
    	public boolean isDir(String line) {
    		return line.startsWith("d");
    	}
    
    	/**
    	 * 檢查文件夾在當前目錄下是否存在
    	 * 
    	 * @param dir
    	 * @return
    	 */
    	public boolean isDirExist(String dir) {
    		String pwd = "";
    		try {
    			pwd = ftpClient.pwd();
    			ftpClient.cd(dir);
    			ftpClient.cd(pwd);
    		} catch (Exception e) {
    			return false;
    		}
    		return true;
    	}
    
    	/**
    	 * 獲取當前路徑
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public String getDir() throws IOException {
    		return this.ftpClient.pwd();
    	}
    
    	/**
    	 * 向上 切換到父級目錄
    	 * 
    	 * @throws IOException
    	 */
    	public void up() throws IOException {
    		if ("/".equals(ftpClient.pwd()) || "http://".equals(ftpClient.pwd())) {
    			return;
    		}
    		this.ftpClient.cdUp();
    	}
    
    	/**
    	 * 刪除文件
    	 * 
    	 * @param fileName
    	 * @return
    	 */
    	public void deleteFile(String fileName) {
    		ftpClient.sendServer("dele " + fileName + "\r\n");// 這個地方一定要注意 加上 \r\n
    		try {
    			if (ftpClient.readServerResponse() != 250)
    				System.out.println("刪除異常");
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 在當前目錄下創建文件夾
    	 * 
    	 * @param dir
    	 * @return
    	 * @throws Exception
    	 */
    	public boolean createDir(String dir) {
    		try {
    			ftpClient.ascii();
    			StringTokenizer s = new StringTokenizer(dir, "/"); // sign
    			s.countTokens();
    			String pathName = ftpClient.pwd();
    			while (s.hasMoreElements()) {
    				pathName = pathName + "/" + (String) s.nextElement();
    				try {
    					ftpClient.sendServer("MKD " + pathName + "\r\n");
    				} catch (Exception e) {
    					e = null;
    					return false;
    				}
    				ftpClient.readServerResponse();
    			}
    			ftpClient.binary();
    			return true;
    		} catch (IOException e1) {
    			e1.printStackTrace();
    			return false;
    		}
    	}
    
    	/**
    	 * 上傳文件
    	 * 
    	 * @param localFile
    	 * @param targetFileName
    	 * @return
    	 */
    	public boolean uploadFile(String localFile, String targetFileName) {
    		boolean result = false;
    		if (this.ftpClient == null) {
    			return false;
    		}
    		TelnetOutputStream tos = null;
    		RandomAccessFile sendFile = null;
    		DataOutputStream dos = null;
    		try {
    			File file = new File(localFile);
    			sendFile = new RandomAccessFile(file, "r");
    			sendFile.seek(0);
    			tos = this.ftpClient.put(targetFileName);
    			dos = new DataOutputStream(tos);
    			int ch = 0;
    			while (sendFile.getFilePointer() < sendFile.length()) {
    				ch = sendFile.read();
    				dos.write(ch);
    			}
    			result = true;
    		} catch (Exception ex) {
    			result = false;
    		} finally {
    			if (tos != null) {
    				try {
    					tos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (dos != null) {
    				try {
    					dos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (sendFile != null) {
    				try {
    					sendFile.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return result;
    	}
    
    	/**
    	 * 上傳文件
    	 * 
    	 * @param localFile
    	 * @param targetFileName
    	 * @return
    	 */
    	public boolean uploadFile(File localFile, String targetFileName) {
    		boolean result = false;
    		if (this.ftpClient == null) {
    			return false;
    		}
    		TelnetOutputStream tos = null;
    		RandomAccessFile sendFile = null;
    		DataOutputStream dos = null;
    		try {
    			sendFile = new RandomAccessFile(localFile, "r");
    			sendFile.seek(0);
    			tos = this.ftpClient.put(targetFileName);
    			dos = new DataOutputStream(tos);
    			int ch = 0;
    			while (sendFile.getFilePointer() < sendFile.length()) {
    				ch = sendFile.read();
    				dos.write(ch);
    			}
    			result = true;
    		} catch (Exception ex) {
    			result = false;
    		} finally {
    			if (tos != null) {
    				try {
    					tos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (dos != null) {
    				try {
    					dos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (sendFile != null) {
    				try {
    					sendFile.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return result;
    	}
    
    	/**
    	 * 上傳本地目錄下的所有文件到服務器上
    	 * 
    	 * @param srcPath
    	 * @param tagPath
    	 * @param level
    	 *            遞歸的級別
    	 * @return
    	 * @see [類、類#方法、類#成員]
    	 */
    	public boolean upPathFile(File srcPathFile, String tagPath) {
    		buildList(tagPath.substring(0, tagPath.lastIndexOf("/")));
    		boolean result = true;
    
    		try {
    			File temp[] = srcPathFile.listFiles();
    			for (int i = 0; i < temp.length; i++) {
    				if (temp[i].isDirectory()) {
    					if (tagPath.lastIndexOf('/') > 0) {
    						result = upPathFile(temp[i], tagPath
    								+ temp[i].getName() + "/");
    					} else {
    						result = upPathFile(temp[i], tagPath + "/"
    								+ temp[i].getName() + "/");
    					}
    				} else {
    					if (tagPath.lastIndexOf('/') > 0) {
    						result = uploadFile(temp[i], tagPath
    								+ temp[i].getName());
    					} else {
    						result = uploadFile(temp[i], tagPath + "/"
    								+ temp[i].getName());
    					}
    
    				}
    			}
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    		return result;
    	}
    
    	/**
    	 * 下載文件
    	 * 
    	 * @param srcFileName
    	 * @param targetFileName
    	 * @return
    	 */
    	public boolean downloadFile(String srcFileName, String targetFileName) {
    		if (this.ftpClient == null) {
    			return false;
    		}
    		TelnetInputStream tis = null;
    		RandomAccessFile getFile = null;
    		boolean result = true;
    		try {
    			File file = new File(targetFileName);
    			getFile = new RandomAccessFile(file, "rw");
    			getFile.seek(0);
    			tis = this.ftpClient.get(srcFileName);
    			DataInputStream dis = new DataInputStream(tis);
    			int ch = 0;
    			while (true) {
    				ch = dis.read();
    				if (ch < 0) {
    					break;
    				}
    				getFile.write(ch);
    			}
    			getFile.close();
    		} catch (IOException e) {
    			result = false;
    		} finally {
    			if (getFile != null) {
    				try {
    					getFile.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (tis != null) {
    				try {
    					tis.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return result;
    	}
    
    	/**
    	 * 下載文件
    	 * 
    	 * @param srcFileName
    	 * @param targetFileName
    	 * @return
    	 */
    	public boolean downloadFile(String srcFileName, File targetFileName) {
    		if (this.ftpClient == null) {
    			return false;
    		}
    		TelnetInputStream tis = null;
    		RandomAccessFile getFile = null;
    		boolean result = true;
    		try {
    			getFile = new RandomAccessFile(targetFileName, "rw");
    			getFile.seek(0);
    			tis = this.ftpClient.get(srcFileName);
    			DataInputStream dis = new DataInputStream(tis);
    			int ch = 0;
    			while (true) {
    				ch = dis.read();
    				if (ch < 0) {
    					break;
    				}
    				getFile.write(ch);
    			}
    			getFile.close();
    		} catch (IOException e) {
    			result = false;
    		} finally {
    			if (getFile != null) {
    				try {
    					getFile.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (tis != null) {
    				try {
    					tis.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return result;
    	}
    
    	/**
    	 * 下載遠程目錄下的所有文件到本地
    	 * 
    	 * @param srcPathFile
    	 *            遠程目錄文件
    	 * @param tagPath
    	 *            本地存放目錄
    	 * @return
    	 * @throws IOException
    	 * @see [類、類#方法、類#成員]
    	 */
    	public boolean downPathFile(String srcPath, String tagPath)
    			throws IOException {
    
    		boolean result = true;
    
    		File tagFile = new File(tagPath);
    		tagFile.mkdirs();
    
    		setPath(srcPath);
    		String tempPath = "";
    		List<String> list = getFileList();
    		for (int i = 0; i < list.size(); i++) {
    			String currPath = list.get(i);
    			String fileName = getFileName(currPath);
    
    			String currPathFul = getDir() + "/" + fileName;
    
    			if (tagPath.lastIndexOf('/') > 0) {
    				tempPath = tagPath
    						+ currPathFul.substring(currPathFul.lastIndexOf("/"),
    								currPathFul.length());
    			} else {
    				tempPath = tagPath
    						+ "/"
    						+ currPathFul.substring(currPathFul.lastIndexOf("/"),
    								currPathFul.length());
    			}
    
    			if (isDir(currPath)) {
    				srcPath = currPathFul + "/";
    				downPathFile(srcPath, tempPath);
    			} else {
    				srcPath = currPathFul;
    				downloadFile(srcPath, tempPath);
    			}
    		}
    
    		return result;
    	}
    
    	/**
    	 * 下載遠程目錄下的所有文件到本地,過濾規則
    	 * 
    	 * @param srcPathFile
    	 *            遠程目錄文件
    	 * @param tagPath
    	 *            本地存放目錄
    	 * @param fileFilter
    	 * 			  下載過濾文件
    	 * @return
    	 * @throws IOException
    	 * @see [類、類#方法、類#成員]
    	 */
    	public boolean downPathFile(String srcPath, String tagPath,
    			FileFilter fileFilter) throws IOException {
    
    		boolean result = true;
    
    		File tagFile = new File(tagPath);
    		tagFile.mkdirs();
    
    		setPath(srcPath);
    		String tempPath = "";
    		List<String> list = getFileList(fileFilter);
    		for (int i = 0; i < list.size(); i++) {
    			String currPath = list.get(i);
    			String fileName = getFileName(currPath);
    
    			String currPathFul = getDir() + "/" + fileName;
    
    			if (tagPath.lastIndexOf('/') > 0) {
    				tempPath = tagPath
    						+ currPathFul.substring(currPathFul.lastIndexOf("/"),
    								currPathFul.length());
    			} else {
    				tempPath = tagPath
    						+ "/"
    						+ currPathFul.substring(currPathFul.lastIndexOf("/"),
    								currPathFul.length());
    			}
    
    			if (isDir(currPath)) {
    				srcPath = currPathFul + "/";
    				downPathFile(srcPath, tempPath, fileFilter);
    			} else {
    				srcPath = currPathFul;
    				downloadFile(srcPath, tempPath);
    			}
    		}
    
    		return result;
    	}
    
    	public String getFileName(String line) {
    		int i;
    		String filename = (String) parseLine(line).get(8);
    		for (i = 9; i < parseLine(line).size(); i++) {
    			filename = filename + " " + ((String) parseLine(line).get(i));
    		}
    		return filename;
    	}
    
    	// 處理getFileList取得的行信息
    	private ArrayList parseLine(String line) {
    		ArrayList s1 = new ArrayList();
    		StringTokenizer st = new StringTokenizer(line, " ");
    		while (st.hasMoreTokens()) {
    			s1.add(st.nextToken());
    		}
    		return s1;
    	}
    
    	/**
    	 * 從FTP文件服務器上下載文件SourceFileName,到本地destinationFileName 所有的文件名中都要求包括完整的路徑名在內
    	 * 
    	 * @param SourceFileName
    	 *            String
    	 * @param destinationFileName
    	 *            String
    	 * @throws Exception
    	 */
    	public void downFile(String SourceFileName, String destinationFileName)
    			throws Exception {
    		ftpClient.binary(); // 一定要使用二進制模式
    		TelnetInputStream ftpIn = ftpClient.get(SourceFileName);
    		byte[] buf = new byte[204800];
    		int bufsize = 0;
    		FileOutputStream ftpOut = new FileOutputStream(destinationFileName);
    		while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
    			ftpOut.write(buf, 0, bufsize);
    		}
    		ftpOut.close();
    		ftpIn.close();
    	}
    
    	/**
    	 * 從FTP文件服務器上下載文件,輸出到字節數組中
    	 * 
    	 * @param SourceFileName
    	 *            String
    	 * @return byte[]
    	 * @throws Exception
    	 */
    	public byte[] downFile(String SourceFileName) throws Exception {
    		ftpClient.binary(); // 一定要使用二進制模式
    		TelnetInputStream ftpIn = ftpClient.get(SourceFileName);
    		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    		byte[] buf = new byte[204800];
    		int bufsize = 0;
    
    		while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
    			byteOut.write(buf, 0, bufsize);
    		}
    		byte[] return_arraybyte = byteOut.toByteArray();
    		byteOut.close();
    		ftpIn.close();
    		return return_arraybyte;
    	}
    
    	/**
    	 * 上傳文件到FTP服務器,destination路徑以FTP服務器的"/"開始,帶文件名、 上傳文件只能使用二進制模式,
    	 * 當文件存在時再次上傳則會覆蓋
    	 * 
    	 * @param source
    	 *            String
    	 * @param destination
    	 *            String
    	 * @throws Exception
    	 */
    	public void upFile(String source, String destination) throws Exception {
    		buildList(destination.substring(0, destination.lastIndexOf("/")));
    		ftpClient.binary(); // 此行代碼必須放在buildList之后
    		TelnetOutputStream ftpOut = ftpClient.put(destination);
    		TelnetInputStream ftpIn = new TelnetInputStream(new FileInputStream(
    				source), true);
    		byte[] buf = new byte[204800];
    		int bufsize = 0;
    		while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
    			ftpOut.write(buf, 0, bufsize);
    		}
    		ftpIn.close();
    		ftpOut.close();
    	}
    
    	/**
    	 * JSP中的流上傳到FTP服務器, 上傳文件只能使用二進制模式,當文件存在時再次上傳則會覆蓋 字節數組做為文件的輸入流,
    	 * 此方法適用于JSP中通過request輸入流來直接上傳文件在RequestUpload類中調用了此方法,
    	 * destination路徑以FTP服務器的"/"開始,帶文件名
    	 * 
    	 * @param sourceData
    	 *            byte[]
    	 * @param destination
    	 *            String
    	 * @throws Exception
    	 */
    	public void upFile(byte[] sourceData, String destination) throws Exception {
    		buildList(destination.substring(0, destination.lastIndexOf("/")));
    		ftpClient.binary(); // 此行代碼必須放在buildList之后
    		TelnetOutputStream ftpOut = ftpClient.put(destination);
    		ftpOut.write(sourceData, 0, sourceData.length);
    		// ftpOut.flush();
    		ftpOut.close();
    	}
    
    	/**
    	 * 在FTP服務器上建立指定的目錄,當目錄已經存在的情下不會影響目錄下的文件,這樣用以判斷FTP
    	 * 上傳文件時保證目錄的存在目錄格式必須以"/"根目錄開頭
    	 * 
    	 * @param pathList
    	 *            String
    	 * @throws Exception
    	 */
    	public void buildList(String pathList) {
    		try {
    			ftpClient.ascii();
    
    			StringTokenizer s = new StringTokenizer(pathList, "/"); // sign
    			int count = s.countTokens();
    			String pathName = "";
    			while (s.hasMoreElements()) {
    				pathName = pathName + (String) s.nextElement();
    				try {
    					ftpClient.sendServer("XMKD " + pathName + "\r\n");
    				} catch (Exception e) {
    					e = null;
    				}
    				int reply = ftpClient.readServerResponse();
    				pathName = pathName + "/";
    			}
    			ftpClient.binary();
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    	}
    
    }

    ?過濾:

    ?

    import java.io.File;
    import java.io.FileFilter;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.util.regex.Pattern;
    
    public class CSFilter implements FileFilter {
    
    	private String patternStr ;
    	
    	//"^CSGET_[0-9]{4}_0085_"+"20120926"+"_[0-9]{3}"
    	private Pattern pattern ;
    
    	public CSVCFilter(String str){
    		this.patternStr = str;
    		this.pattern = Pattern.compile(patternStr);
    	}
    	public boolean accept(File pathname) {
    		String strName = pathname.getName();
    		if (!isDir(strName)) {
    			strName = getFileName(strName);
    			System.out.println(strName);
    			return pattern.matcher(strName).matches();
    		}
    		return true;
    	}
    
    	public boolean isDir(String strName) {
    		return ((String) parseLine(strName).get(0)).indexOf("d") != -1;
    	}
    
    	public String getFileName(String line) {
    		int i;
    		String filename = (String) parseLine(line).get(8);
    		for (i = 9; i < parseLine(line).size(); i++) {
    			filename = filename + " " + ((String) parseLine(line).get(i));
    		}
    		return filename;
    	}
    
    	// 處理getFileList取得的行信息
    	private ArrayList parseLine(String line) {
    		ArrayList s1 = new ArrayList();
    		StringTokenizer st = new StringTokenizer(line, " ");
    		while (st.hasMoreTokens()) {
    			s1.add(st.nextToken());
    		}
    		return s1;
    	}
    
    	public String getFileSize(String line) {
    		return (String) parseLine(line).get(4);
    	}
    
    	public String getFileDate(String line) {
    		ArrayList a = parseLine(line);
    		return (String) a.get(5) + " " + (String) a.get(6) + " "
    				+ (String) a.get(7);
    	}
    
    }

    ?

    下載速度提升

    ?

    public boolean downloadFile(String srcFileName, File targetFileName)
    {
    //.....
    
    //下載速度太慢,用如下方式進行提升
                            byte[] recvbuf = new byte[1024];
    			while((ch = dis.read(recvbuf)) > 0){
    				getFile.write(recvbuf,0,ch);
    			}
    
    //			while (true) {
    //				ch = dis.read();
    //				if (ch < 0) {
    //					break;
    //				}
    //				getFile.write(ch);
    //			}
    
    
    
    //...
    
    }
    ?

    ?

    ?



    已有 0 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-10-10 16:26 李凡 閱讀(355) | 評論 (0)編輯 收藏

    ?服務器端:

    ?

    ?

     // 1. 分配一個 ServerSocketChannel 文件描述符
                serverChannel = ServerSocketChannel.open();
    
                // 2. 從 ServerSocketChannel里獲取一個對于的 socket
                serverSocket = serverChannel.socket();
    
                // 3. 生成一個 Selector
                selector = Selector.open();
    
                // 4. 把 socket 綁定到端口上
                serverSocket.bind(new InetSocketAddress(iport));
    
                // 5. serverChannel 未非bolck
                serverChannel.configureBlocking(false);
    
                // 6. 通過Selector注冊ServerSocketChannel: 只能注冊 accept
                // 而SocketChannel可以注冊CONNENCT,READ,WRITE ; register -> validOps
                // 在各個子類實現不同
                serverChannel.register(selector, SelectionKey.OP_ACCEPT);
                while (true) {
    			try {
    				// 獲得IO準備就緒的channel數量
    				int n = selector.select();
    
    				// 沒有channel準備就緒,繼續執行
    				if (n == 0) {
    					continue;
    				}
    
    				// 用一個iterator返回Selector的selectedkeys
    				Iterator it = selector.selectedKeys().iterator();
    
    				// 處理每一個SelectionKey
    				while (it.hasNext()) {
    					SelectionKey key = (SelectionKey) it.next();
    
    					// 判斷是否有新的連接到達
    					if (key.isAcceptable()) {
    						
    						// 返回SelectionKey的ServerSocketChannel
    						ServerSocketChannel server = (ServerSocketChannel) key
    								.channel();
    						System.out.println("有連接");
    						SocketChannel channel = server.accept();
    						
    						registerChannel(selector, channel, SelectionKey.OP_READ);
    						
    						doWork(channel);
    					}
    
    					// 判斷是否有數據在此channel里需要讀取
    					if (key.isReadable()) {
    						processData(key);
    					}
    				}
    
    				// 刪除 selectedkeys
    				it.remove();
    
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}

    ?

    ?

    ?

    ?客戶端:

    ?

    ?

      //打開socket通道
    		SocketChannel socketChannel = SocketChannel.open();
    		//設置非阻塞方式
    		socketChannel.configureBlocking(false);
    		//打開選擇器
    		Selector selector = Selector.open();
    		//注冊連接到服務器socket動作
    		socketChannel.register(selector, SelectionKey.OP_CONNECT);
    		//連接
    		socketChannel.connect( new InetSocketAddress("localhost",9988));
    		
    		Set<SelectionKey> selectkeySets;
    		SelectionKey selectionKey;
    		Iterator<SelectionKey> iterator;
    		
    		//與服務器通信通道
    		SocketChannel clientChannel ;
    
    	       while(true){
    			//選擇一組建,其相應的通道已為I/O操作準備就緒
    			//此方法執行處于阻塞模式的選擇操作
    			selector.select(TIME_OUT);
    			
    			//返回此選擇器的已選擇鍵集。
    			selectkeySets = selector.selectedKeys();
    			iterator = selectkeySets.iterator();
    			
    			
    			while(iterator.hasNext()){
    				selectionKey = iterator.next();
    				
    				if (selectionKey.isConnectable()) {
                                      clientChannel = (SocketChannel)selectionKey.channel();
    					// 判斷此通道上是否正在進行連接操作。  
                                      // 完成套接字通道的連接過程。  
    					if (clientChannel.isConnectionPending()) {//判斷此通道上是否正在進行連接操作
    						clientChannel.finishConnect();  //完成套接字通道的連接過程
                                       
                                      }
                                      clientChannel.register(selector, SelectionKey.OP_WRITE);
                                }else if (selectionKey.isReadable()) {
    					clientChannel = (SocketChannel)selectionKey.channel();
    					//將緩沖區清空
    					receiveBuffer.clear();
    					//讀取服務器發送來的數據庫到緩沖區
    					count = clientChannel.read(receiveBuffer);//count 讀取到的字節數
    					if (count > 0) {
    						clientChannel.register(selector, SelectionKey.OP_WRITE);
    					}
                                }else if (selectionKey.isWritable()) {
    					sendBuffer.clear();
    					clientChannel = (SocketChannel)selectionKey.channel();
    					clientChannel.write(sendBuffer);
    					System.out.println("客戶端向服務器發送數據:"+sendText);
    					clientChannel.register(selector, SelectionKey.OP_READ);
                                }
                         }
                     }
    
    

    ?



    已有 0 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-09-28 16:31 李凡 閱讀(294) | 評論 (0)編輯 收藏

    服務器端:
    ????

    // 創建一個非阻塞的server端socket ,用NIO
    		SocketAcceptor acceptor = new NioSocketAcceptor();
    
    		// 創建接收數據的過濾器
    		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
    
    		// 設定這個過濾器一行一行(\r\n)的讀數據
    		chain.addLast("myChin", new ProtocolCodecFilter(
    				new TextLineCodecFactory()));
    
    		//設定服務器端的消息處理器,一個SamplMinaServerHandler對象(自己實現)繼承IoHandlerAdapter
    		acceptor.setHandler(new IoHandlerAdapter(){
    			//當一個客端端連結進入時
    			@Override
    			public void sessionOpened(IoSession session) throws Exception {
    				// TODO Auto-generated method stub
    				System.out.println("incomming client : "+session.getRemoteAddress());
    			}
    			
    			//當一個客戶端關閉時
    			@Override
    			public void sessionClosed(IoSession session) throws Exception {
    				// TODO Auto-generated method stub
    				System.out.println("on client disconnect : "+session.getRemoteAddress());
    			}
    
    			//當客戶端發送的消息到達時
    			@Override
    			public void messageReceived(IoSession session, Object message)
    					throws Exception {
    				// TODO Auto-generated method stub
    				String s =  (String)message;
    				System.out.println("收到客戶端發來的消息:"+s);
    				//測試將消息回給客戶端
    				session.write(s+count);
    				count ++;
    			}
    			private int count =0;
    		});
    		//端口號
    		int bindPort= 9988;
    		
    		//綁定打開,啟動服務器
    		acceptor.bind(new InetSocketAddress(bindPort));
    		
    		System.out.println("Mina Server is listing on:="+bindPort);

    ??
    ???
    ???
    ??客戶端:
    ???

    // create TCP/IP connector
    		NioSocketConnector connector = new NioSocketConnector();
    
    		// 創建接收數據的過濾器
    		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
    
    		// 設定這個過濾器將一行一行(/r/n)的讀取數據
    		chain.addLast("myChin", new ProtocolCodecFilter(
    				new TextLineCodecFactory()));
    
    		// 設定服務器端的消息處理器:一個SamplMinaServerHandler對象,
    		connector.setHandler(new IoHandlerAdapter(){
    			@Override
    			public void messageReceived(IoSession session, Object message)
    					throws Exception {
    				// 我們己設定了服務器解析消息的規則是一行一行讀取,這里就可轉為String:
    				String s = (String) message;
    				// Write the received data back to remote peer
    				System.out.println("服務器發來的收到消息: " + s);
    				// 測試將消息回送給客戶端
    				session.write(s);
    			}
    
    			@Override
    			public void sessionClosed(IoSession session) throws Exception {
    				// TODO Auto-generated method stub
    				System.out.println("one Clinet Disconnect !");
    			}
    
    			@Override
    			public void sessionOpened(IoSession session) throws Exception {
    				// TODO Auto-generated method stub
    				System.out.println("incomming client  " + session.getRemoteAddress());
    				session.write("我來啦........");
    			}
    		});
    		
    		// Set connect timeout.
    		connector.setConnectTimeout(30);
    		
    		// 連結到服務器:
    		ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",
    				9988));
    		
    		// Wait for the connection attempt to be finished.
    		cf.awaitUninterruptibly();
    		cf.getSession().getCloseFuture().awaitUninterruptibly();
    		connector.dispose();

    ?
    ???
    ???
    ???????



    已有 0 人發表留言,猛擊->>這里<<-參與討論


    ITeye推薦



    posted @ 2012-09-28 10:52 李凡 閱讀(194) | 評論 (0)編輯 收藏

    主站蜘蛛池模板: 99久久免费国产精品特黄| 中国一级毛片免费看视频| 99re在线免费视频| 久久亚洲伊人中字综合精品| 一个人看的免费视频www在线高清动漫| 国产成人免费片在线视频观看| 亚洲中文字幕无码av永久| 手机在线免费视频| 亚洲伊人久久大香线蕉| 亚洲三级在线免费观看| 亚洲制服在线观看| 成年性生交大片免费看| 国产亚洲漂亮白嫩美女在线| 亚洲?V无码乱码国产精品| 一个人看www免费高清字幕| 曰韩亚洲av人人夜夜澡人人爽| 视频免费在线观看| 亚洲美女aⅴ久久久91| 可以免费看的卡一卡二| 日本免费人成网ww555在线| 久久精品国产亚洲AV网站| 少妇太爽了在线观看免费视频 | 亚洲av无码专区在线观看亚| 午夜免费福利网站| 成年免费a级毛片| 国产亚洲精品精华液| 日韩免费一区二区三区在线播放| 亚洲日韩精品国产3区| 亚洲精品尤物yw在线影院| 国产一区二区免费视频| 亚洲一区二区三区乱码在线欧洲| 免费看国产一级特黄aa大片| 成人性做爰aaa片免费看| 亚洲av无码片区一区二区三区| 国产成人无码区免费A∨视频网站| 精品多毛少妇人妻AV免费久久| 亚洲精品国产肉丝袜久久| 日本免费一本天堂在线| 免费黄网站在线看| 亚洲av综合av一区二区三区| 亚洲日韩精品无码专区网址|