锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
聽
聽
聽
緇熶竴鎺ュ彛錛?/p>
聽
public interface HelloApi { public void sayHello(); }
聽
聽
涓銆佸歡榪熷垵濮嬪寲錛?/p>
聽
/** * 寤惰繜鍒濆鍖朆ean * 寤惰繜鍒濆鍖栦篃鍙仛鎯版у垵濮嬪寲錛屾寚涓嶆彁鍓嶅垵濮嬪寲Bean錛岃屾槸鍙湁鍦ㄧ湡姝d嬌鐢ㄦ椂鎵嶅垱寤哄強鍒濆鍖朆ean銆? * 閰嶇疆鏂瑰紡寰堢畝鍗曞彧闇鍦?lt;bean>鏍囩涓婃寚瀹?鈥渓azy-init鈥?灞炴у間負鈥渢rue鈥濆嵆鍙歡榪熷垵濮嬪寲Bean銆? */ public class DiLazyInit implements HelloApi{ public void sayHello() { System.out.println("say DiInitDestory"); } public DiLazyInit(){ System.out.println("鍒濆鍖?DiInitDestory"); } }
聽
聽
閰嶇疆寤惰繜鍒濆鍖栵細
聽
聽
<!-- 寤惰繜鍒濆鍖朆ean 寤惰繜鍒濆鍖栦篃鍙仛鎯版у垵濮嬪寲錛屾寚涓嶆彁鍓嶅垵濮嬪寲Bean錛岃屾槸鍙湁鍦ㄧ湡姝d嬌鐢ㄦ椂鎵嶅垱寤哄強鍒濆鍖朆ean銆? 閰嶇疆鏂瑰紡寰堢畝鍗曞彧闇鍦?lt;bean>鏍囩涓婃寚瀹?鈥渓azy-init鈥?灞炴у間負鈥渢rue鈥濆嵆鍙歡榪熷垵濮嬪寲Bean銆?--> <bean id="lazyinitDi" class="com.diinit.DiLazyInit" lazy-init="true"> </bean>
聽
聽junit 榪涜嫻嬭瘯錛?/p>
聽
@Test public void testLazyInit(){ ApplicationContext context = new ClassPathXmlApplicationContext("initdepends.xml"); HelloApi lazyInit = context.getBean("lazyinitDi",HelloApi.class); lazyInit.sayHello(); System.out.println(""); }聽
聽
娉ㄦ剰榪欎釜鏃跺欑殑杈撳嚭緇撴灉錛?/p>
聽
聽
鍒濆鍖?DiLazyInit
say DiLazyInit
聽
聽
聽
聽
浜屻?鍙互鎸囧畾鍒濆鍖栧拰閿姣佺殑欏哄簭
聽
聽
/* 浣跨敤depends-on 鏄寚 鎸囧畾Bean鍒濆鍖栧強閿姣佹椂鐨勯『搴忥紝浣跨敤depends-on灞炴ф寚瀹氱殑Bean瑕佸厛鍒濆鍖栧畬姣? * 鍚庢墠鍒濆鍖栧綋鍓岯ean錛岀敱浜庡彧鏈夆渟ingleton鈥滲ean鑳借Spring綆$悊閿姣侊紝鎵浠ュ綋鎸囧畾鐨凚ean閮芥槸鈥渟ingleton鈥? * 鏃訛紝浣跨敤depends-on灞炴ф寚瀹氱殑Bean瑕佸湪鎸囧畾鐨凚ean涔嬪悗閿姣併? * 鈥渄ecorator鈥濇寚瀹氫簡鈥渄epends-on鈥濆睘鎬т負鈥渓azyinitDi鈥濓紝鎵浠ュ湪鈥渄ecorator鈥滲ean鍒濆鍖栦箣鍓嶈鍏堝垵 * 濮嬪寲鈥渓azyinitDi鈥濓紝鑰屽湪閿姣佲渓azyinitDi鈥濅箣鍓嶅厛瑕侀攢姣佲渄ecorator鈥濓紝澶у娉ㄦ剰涓涓嬮攢姣侀『搴忥紝涓庢枃妗d笂鐨勪笉絎︺? * 鈥渄epends-on鈥濆睘鎬у彲浠ユ寚瀹氬涓狟ean錛岃嫢鎸囧畾澶氫釜Bean鍙互鐢ㄢ?鈥濄佲?鈥濄佺┖鏍煎垎鍓層? * * 閭b渄epends-on鈥濇湁浠涔堝ソ澶勫憿錛? * 涓昏鏄粰鍑烘槑紜殑鍒濆鍖栧強閿姣侀『搴忥紝姣斿瑕佸垵濮嬪寲鈥渄ecorator鈥濇椂瑕佺‘淇濃渓azyinitDi鈥滲ean鐨勮祫婧愬噯澶囧ソ浜嗭紝 * 鍚﹀垯浣跨敤鈥渄ecorator鈥濇椂浼氱湅涓嶅埌鍑嗗鐨勮祫婧愶紱鑰屽湪閿姣佹椂瑕佸厛鍦ㄢ渄ecorator鈥滲ean鐨勬妸瀵光渉elloApi鈥濊祫婧愮殑寮曠敤閲? * 鏀炬帀鎵嶈兘閿姣佲渓azyinitDi鈥濓紝鍚﹀垯鍙兘閿姣?鈥渓azyinitDi鈥濇椂鑰屸渄ecorator鈥濊繕淇濇寔鐫璧勬簮璁塊棶錛岄犳垚璧勬簮涓嶈兘閲婃斁鎴栭噴鏀鵑敊璇? */ 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鎸囧畾鍒濆鍖栧拰閿姣侀『搴忥細
聽
<!-- 鍒濆鍖栧強閿姣佹椂鐨勯『搴? 鈥渄ecorator鈥濇寚瀹氫簡鈥渄epends-on鈥濆睘鎬т負鈥渓azyinitDi鈥濓紝鎵浠ュ湪鈥渄ecorator鈥滲ean鍒濆鍖栦箣鍓? 瑕佸厛鍒濆鍖栤渓azyinitDi鈥濓紝鑰屽湪閿姣佲渓azyinitDi鈥濅箣鍓嶅厛瑕侀攢姣佲渄ecorator鈥濓紝澶у娉ㄦ剰涓涓嬮攢姣侀『搴?--> <bean id="decorator" class="com.diinit.ApiDecorator" depends-on="lazyinitDi"> <property name="helloApi"> <ref bean="lazyinitDi" /> </property> </bean>聽
聽
聽
聽junit 榪涜嫻嬭瘯錛?/p>
聽
@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(); }聽
聽
娉ㄦ剰榪欎釜鏃跺欑殑杈撳嚭緇撴灉錛?/p>
聽
聽
鍒濆鍖?DiLazyInit
鍒濆鍖?ApiDecorator 聽 聽 聽 聽 聽 聽//涔熸槸涓婇潰鍚屾牱鐨勬祴璇曞嚱鏁?testLazyInit()錛屽悓鏍風殑閰嶇疆 聽榪欏彞鏄鎵撳嵃鍑烘潵鐨?/strong>
say DiLazyInit
聽
鍒濆鍖?DiLazyInit
鍒濆鍖?ApiDecorator
say ApiDecorator
say DiLazyInit
聽
聽
聽
榪欑獊鐒跺鍑烘潵鐨勬墦鍗扮粨鏋滐紝璇存槑榪涜浜咥piDecorator鐨勫璞$殑鍒涘緩錛?/p>
浣嗘槸鍦ㄧ涓涓厤緗腑涔熸病娑夊強鍒奧燗piDecorator 綾葷殑鍔犺澆錛屾敞鍏?聽銆?/p>
聽
浠涔堝師鍥犻犳垚鐨勫憿錛?span style="color: #0000ff;">鏄竴縐嶉殣钘忕殑娉ㄥ叆錛?緇х畫鎺㈢儲涓?...
聽
聽
聽
聽
聽
涓銆佹瀯閫犲櫒娉ㄥ叆鏂瑰紡錛?/strong>
錛?錛夐氳繃鈥?<constructor-arg>鈥濇爣絳劇殑ref灞炴ф潵寮曠敤鍏朵粬Bean
聽
錛?錛夐氳繃鈥?<constructor-arg>鈥濇爣絳劇殑瀛?lt;ref>鏍囩鏉ュ紩鐢ㄥ叾浠朆ean錛屼嬌鐢╞ean灞炴ф潵鎸囧畾寮曠敤鐨凚ean
浜屻乻etter娉ㄥ叆鏂瑰紡錛?/strong>
錛?錛夐氳繃鈥?<property>鈥濇爣絳劇殑ref灞炴ф潵寮曠敤鍏朵粬Bean
錛?錛夐氳繃鈥?<property>鈥濇爣絳劇殑瀛?lt;ref>鏍囩鏉ュ紩鐢ㄥ叾浠朆ean錛屼嬌鐢╞ean灞炴ф潵鎸囧畾寮曠敤鐨凚ean
聽
聽
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; } }
聽閰嶇疆娉ㄥ叆寮曠敤鍏朵粬鐨刡ean
聽
<!-- 寮曠敤鍏朵粬鐨刡ean榪涜娉ㄥ叆 --> <bean id="helloBean" class="com.dilist.HelloDiBean"> <constructor-arg index="0" ref="mapBean" /> <property name="helloApi2"> <ref bean="properBean" /> </property> </bean>聽
鍏朵粬寮曠敤bean 鐨勯珮綰х敤娉曪細
聽
/** * Spring榪樻彁渚涗簡鍙﹀涓ょ鏇撮珮綰х殑閰嶇疆鏂瑰紡錛?lt;ref local=鈥濃?>鍜?lt;ref parent=鈥濃?>錛? * 錛?錛?lt;ref local=鈥濃?>閰嶇疆鏂瑰紡錛氱敤浜庡紩鐢ㄩ氳繃<bean id=鈥漛eanName鈥?gt;鏂瑰紡涓氳繃id灞炴ф寚瀹氱殑Bean錛? * 瀹冭兘鍒╃敤XML瑙f瀽鍣ㄧ殑楠岃瘉鍔熻兘鍦ㄨ鍙栭厤緗枃浠舵椂鏉ラ獙璇佸紩鐢ㄧ殑Bean鏄惁瀛樺湪銆? * 鍥犳濡傛灉鍦ㄥ綋鍓嶉厤緗枃浠朵腑鏈夌浉浜掑紩鐢ㄧ殑Bean鍙互閲囩敤<ref local>鏂瑰紡浠庤屽鏋滈厤緗敊璇兘鍦ㄥ紑鍙戣皟璇曟椂灝卞彂鐜伴敊璇? * 錛?錛?lt;ref parent=鈥濃?>閰嶇疆鏂瑰紡錛氱敤浜庡紩鐢ㄧ埗瀹瑰櫒涓殑Bean錛屼笉浼氬紩鐢ㄥ綋鍓嶅鍣ㄤ腑鐨凚ean錛? * 褰撶劧鐖跺鍣ㄤ腑鐨凚ean鍜屽綋鍓嶅鍣ㄧ殑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錛?/span>
聽
<!-- 娉ㄥ叆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 寤哄拰鍊奸兘鏄疭tring綾誨瀷 --> <prop key="2">2</prop> </props> </property> <property name="properties2"> <value> <!-- 鍒嗛殧絎﹀彲浠ユ槸 鈥滄崲琛屸濄佲滐紱鈥濄佲滐紝鈥?涓嶅緩璁鏂瑰紡錛屼紭鍏堥夋嫨絎竴縐嶆柟寮?--> 1=11 2=22;<!-- 榪欐牱鐨勫垎闅旂濂藉儚娌$敤 --> 3=33, 4=44 </value> </property> </bean> <!-- Spring榪樻彁渚涗簡鍙﹀涓ょ鏇撮珮綰х殑閰嶇疆鏂瑰紡錛?lt;ref local=鈥濃?>鍜?lt;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錛?/span>
聽
<!-- 娉ㄥ叆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 寤哄拰鍊奸兘鏄疭tring綾誨瀷 --> <prop key="2">3aas</prop> </props> </property> <property name="properties2"> <value> <!-- 鍒嗛殧絎﹀彲浠ユ槸 鈥滄崲琛屸濄佲滐紱鈥濄佲滐紝鈥?涓嶅緩璁鏂瑰紡錛屼紭鍏堥夋嫨絎竴縐嶆柟寮?--> 1=111 2=222;<!-- 榪欐牱鐨勫垎闅旂濂藉儚娌$敤 --> 3=333, 4=444 </value> </property> </bean>聽
璋冪敤澶?鍒╃敤鍔犺澆鐖跺鍣ㄧ殑鏂瑰紡錛屾敞鍏ョ埗瀹瑰櫒涓殑Bean錛?/p>
聽
聽
@Test public void testDiBeanHigh() { // 浠lasses涓烘牴鐩綍綆楄搗 // 璇誨彇閰嶇疆鏂囦歡瀹炰緥鍖栦竴涓狪oc瀹瑰櫒 // 鍒濆鍖栫埗瀹瑰櫒 ApplicationContext parentContext = new ClassPathXmlApplicationContext( "helloworldParent.xml"); // 鍒濆鍖栧綋鍓嶅鍣? ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "helloworld.xml" }, parentContext); // 鏋勯?+ setter娉ㄥ叆 寮曠敤鍏朵粬鐨刡ean娉ㄥ叆 HelloApi helloApi = context.getBean("helloHigh", HelloApi.class); helloApi.sayHello(); }
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 鍔ㄦ佺敓鎴恈lass 騫惰繘琛屾嫤鎴?/pre>聽
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鎺ㄨ崘
聽
聽
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; } /** * 浠嶧TP鏂囦歡鏈嶅姟鍣ㄤ笂涓嬭澆鏂囦歡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(); } /** * 浠嶧TP鏂囦歡鏈嶅姟鍣ㄤ笂涓嬭澆鏂囦歡錛岃緭鍑哄埌瀛楄妭鏁扮粍涓? * * @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; } /** * 涓婁紶鏂囦歡鍒癋TP鏈嶅姟鍣?destination璺緞浠TP鏈嶅姟鍣ㄧ殑"/"寮濮嬶紝甯︽枃浠跺悕銆?涓婁紶鏂囦歡鍙兘浣跨敤浜岃繘鍒舵ā寮忥紝 * 褰撴枃浠跺瓨鍦ㄦ椂鍐嶆涓婁紶鍒欎細瑕嗙洊 * * @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(); // 姝よ浠g爜蹇呴』鏀懼湪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鏈嶅姟鍣? 涓婁紶鏂囦歡鍙兘浣跨敤浜岃繘鍒舵ā寮忥紝褰撴枃浠跺瓨鍦ㄦ椂鍐嶆涓婁紶鍒欎細瑕嗙洊 瀛楄妭鏁扮粍鍋氫負鏂囦歡鐨勮緭鍏ユ祦, * 姝ゆ柟娉曢傜敤浜嶫SP涓氳繃request杈撳叆嫻佹潵鐩存帴涓婁紶鏂囦歡鍦≧equestUpload綾諱腑璋冪敤浜嗘鏂規硶錛? * destination璺緞浠TP鏈嶅姟鍣ㄧ殑"/"寮濮嬶紝甯︽枃浠跺悕 * * @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(); // 姝よ浠g爜蹇呴』鏀懼湪buildList涔嬪悗 TelnetOutputStream ftpOut = ftpClient.put(destination); ftpOut.write(sourceData, 0, sourceData.length); // ftpOut.flush(); ftpOut.close(); } /** * 鍦‵TP鏈嶅姟鍣ㄤ笂寤虹珛鎸囧畾鐨勭洰褰?褰撶洰褰曞凡緇忓瓨鍦ㄧ殑鎯呬笅涓嶄細褰卞搷鐩綍涓嬬殑鏂囦歡,榪欐牱鐢ㄤ互鍒ゆ柇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(); } } }
聽榪囨護錛?/p>
聽
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); // } //... }聽
聽
聽
聽
聽
// 1. 鍒嗛厤涓涓?ServerSocketChannel 鏂囦歡鎻忚堪絎? serverChannel = ServerSocketChannel.open(); // 2. 浠?ServerSocketChannel閲岃幏鍙栦竴涓浜庣殑 socket serverSocket = serverChannel.socket(); // 3. 鐢熸垚涓涓?Selector selector = Selector.open(); // 4. 鎶?socket 緇戝畾鍒扮鍙d笂 serverSocket.bind(new InetSocketAddress(iport)); // 5. serverChannel 鏈潪bolck serverChannel.configureBlocking(false); // 6. 閫氳繃Selector娉ㄥ唽ServerSocketChannel: 鍙兘娉ㄥ唽 accept // 鑰孲ocketChannel鍙互娉ㄥ唽CONNENCT,READ,WRITE ; register -> validOps // 鍦ㄥ悇涓瓙綾誨疄鐜頒笉鍚? serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { try { // 鑾峰緱IO鍑嗗灝辯華鐨刢hannel鏁伴噺 int n = selector.select(); // 娌℃湁channel鍑嗗灝辯華,緇х畫鎵ц if (n == 0) { continue; } // 鐢ㄤ竴涓猧terator榪斿洖Selector鐨剆electedkeys Iterator it = selector.selectedKeys().iterator(); // 澶勭悊姣忎竴涓猄electionKey while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // 鍒ゆ柇鏄惁鏈夋柊鐨勮繛鎺ュ埌杈? if (key.isAcceptable()) { // 榪斿洖SelectionKey鐨凷erverSocketChannel ServerSocketChannel server = (ServerSocketChannel) key .channel(); System.out.println("鏈夎繛鎺?); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ); doWork(channel); } // 鍒ゆ柇鏄惁鏈夋暟鎹湪姝hannel閲岄渶瑕佽鍙? 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); } } }
聽
// 鍒涘緩涓涓潪闃誨鐨剆erver绔痵ocket 錛岀敤NIO SocketAcceptor acceptor = new NioSocketAcceptor(); // 鍒涘緩鎺ユ敹鏁版嵁鐨勮繃婊ゅ櫒 DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); // 璁懼畾榪欎釜榪囨護鍣ㄤ竴琛屼竴琛?\r\n)鐨勮鏁版嵁 chain.addLast("myChin", new ProtocolCodecFilter( new TextLineCodecFactory())); //璁懼畾鏈嶅姟鍣ㄧ鐨勬秷鎭鐞嗗櫒,涓涓猄amplMinaServerHandler瀵硅薄(鑷繁瀹炵幇)緇ф壙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())); // 璁懼畾鏈嶅姟鍣ㄧ鐨勬秷鎭鐞嗗櫒:涓涓猄amplMinaServerHandler瀵硅薄, 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();
聽
聽聽聽
聽聽聽
聽聽聽聽聽聽聽
聽
鍒嗗尯 聽鐢ㄦ椂闂磋繘琛屽垎鍖?/p>
宸叉湁 0 浜哄彂琛ㄧ暀璦錛岀寷鍑?>>榪欓噷<<-鍙備笌璁ㄨ
ITeye鎺ㄨ崘
聽
public static int PORT = 8888; ServerSocketChannel serverChannel; ServerSocket serverSocket; Selector selector;
聽
鍒濆鍖栵細
// 1. 鍒嗛厤涓涓?ServerSocketChannel 鏂囦歡鎻忚堪絎? serverChannel = ServerSocketChannel.open(); // 2. 浠?ServerSocketChannel閲岃幏鍙栦竴涓浜庣殑 socket serverSocket = serverChannel.socket(); // 3. 鐢熸垚涓涓?Selector selector = Selector.open(); // 4. 鎶?socket 緇戝畾鍒扮鍙d笂 serverSocket.bind(new InetSocketAddress(iport)); // 5. serverChannel 鏈潪bolck serverChannel.configureBlocking(false); // 6. 閫氳繃Selector娉ㄥ唽ServerSocketChannel: 鍙兘娉ㄥ唽 accept // 鑰孲ocketChannel鍙互娉ㄥ唽CONNENCT,READ,WRITE ; register -> validOps // 鍦ㄥ悇涓瓙綾誨疄鐜頒笉鍚? serverChannel.register(selector, SelectionKey.OP_ACCEPT);
聽
寮鍚湇鍔★細
while (true) { try { // 鑾峰緱IO鍑嗗灝辯華鐨刢hannel鏁伴噺 int n = selector.select(); // 娌℃湁channel鍑嗗灝辯華,緇х畫鎵ц if (n == 0) { continue; } // 鐢ㄤ竴涓猧terator榪斿洖Selector鐨剆electedkeys Iterator it = selector.selectedKeys().iterator(); // 澶勭悊姣忎竴涓猄electionKey while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // 鍒ゆ柇鏄惁鏈夋柊鐨勮繛鎺ュ埌杈? if (key.isAcceptable()) { // 榪斿洖SelectionKey鐨凷erverSocketChannel ServerSocketChannel server = (ServerSocketChannel) key .channel(); System.out.println("鏈夎繛鎺?); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ); doWork(channel); } // 鍒ゆ柇鏄惁鏈夋暟鎹湪姝hannel閲岄渶瑕佽鍙? if (key.isReadable()) { processData(key); } } // 鍒犻櫎 selectedkeys it.remove(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
聽