이 기사에서는 참조를 위해 특정 Java 파일 업로드 서버 및 클라이언트의 특정 코드를 공유합니다. 특정 내용은 다음과 같습니다
파일 업로드 서버 :
/ *** TCP 프로토콜을 사용하여 업로드 함수를 구현하기 위해 서버 측* 아이디어 :* 새 서버 소켓 생성* 클라이언트가 연결 될 때까지 대기합니다* 연결 후 하위 스레드를 시작한 후 하위 스레드* 루핑* @author yajun**/ public uploadserver {public static void main (string [] args) {up uploadser (); uploadthread 명령 = new uploadTheRdread (); server.start (명령); } /*** 함수 : 연결 수락, 하위 스레드를 시작, 루프* @param 명령 다운로드하는 데 사용되는 자식 스레드 객체를 다운로드합니다. 소켓 트랜스 소켓; // 비즈니스 로직 시도 {serversocket = new Serversocket (55555); while (true) {system.out.println ( "연결 대기 ..."); transsocket = serversocket.accept (); int i = 0; i ++; System.out.println ( "th"+i+"Connection"); // 다운로드 후 스레드를 닫아야합니까? ? ? Command.SetSocket (TransSocket); executor.newfixedthreadpool (5) .Execute (명령); } // Exception Catch} catch (ioexception e) {e.printstacktrace (); // resource를 닫습니다} 마지막으로 {try {serversocket.close (); } catch (ioexception e) {e.printstacktrace (); }} // try of try} // connect of connect @test public void testConnect () {// 테스트 작업 : 먼저 서버 측을 실행 한 다음 클라이언트를 여러 번 실행하십시오. 서버 세그먼트는 어린이 스레드를 지속적으로 생성 할 수 있으며 테스트가 성공적입니다. // 테스트 준비 : 스레드를 구성하여 다운로드를 시뮬레이션합니다. uploadthread ordly 명령 = new UploadTheRdread (); 시작 (명령); } @test public void testdown ()는 ioexception {byte [] buf; BytearrayinputStream bis; String str = "canglaoshi.avi/ncontent, 내용, 내용"; buf = str.getBytes (); bis = 새로운 Bytearrayinputstream (Buf); uploadthread ut = new uploadthread (); ut.down (bis); }} // 각 전송 작업 클래스를 완료하는 서브 스레드 업로드 스레드는 런 가능 {소켓 소켓; public uploadthread () {} public uploadthread (소켓 소켓) {this.socket = socket; } @override public void Run () {inputStream in; try {in = socket.getInputStream (); 다운 (in); // 예외 처리} catch (ioException e) {e.printstacktrace (); } 마침내 {try {socket.close (); } catch (ioexception e) {e.printstacktrace (); }} // 테스트 코드/*try {thread.sleep (5000); System.out.println (thread.currentthread (). getName ()+", copyname ()+"); } catch (InterruptedException e) {e.printstacktrace (); }*/} // 실행 종료 public void setsocket (소켓 소켓) {this.socket = socket; } // 방법 다운로드/*** 목표 : 로컬* 아이디어에 입력 스트림에 데이터를 쓰기* 1. 입력 스트림을 얻으십시오. 입력 스트림에서 소켓에서 직접 얻는 대신 입력 스트림에서 전달하는 것이 가장 좋습니다.* 2를 사용하여 입력 스트림에서 파일 이름을 읽습니다. ioException */public void down (inputStream in)은 ioexception {// 로컬 변수 char ch; char [] namearr = new char [256]; 바이트 [] buf = 새로운 바이트 [1024]; 문자열 이름 = ""; outputStream out = null; // 비즈니스 로직 시도 {// 1 단계 : 파일 이름을 가져 와서 파일 출력 스트림 int i = 0; while ((ch = (char) in.read ())! = '/n') {namearr [i ++] = ch; } //name=namearr.tostring() ;//this 문장은 문자 배열을 문자열로 변환 할 수 없습니다. 다음 문을 사용해야합니다. namearr (new String); System.out.println ( "다운로드 할 파일은"+name); out = new FileOutputStream ( "src // down //"+name); // 2 단계 : 입력 스트림에 다른 내용을 파일에 int len에 씁니다. while ((len = in.read (buf))! = -1) {out.write (buf, 0, len); } out.flush (); // 예외 캡처} catch (ioException e) {e.printstacktrace (); // resource} 마침내 {// 질문 : 두 캡처를 구성 할 수 있습니까? 스트림을 닫을 때 예외를 다루는 방법은 무엇입니까? 넣다(); out.close (); } // debug system.out.println (이름); }} // uploadthread의 끝 파일 업로드 클라이언트 :
/ *** TCP 프로토콜을 사용하여 업로드 기능을 구현하는 클라이언트* @Author Yajun*/ public class uploadclient {public static void main (string [] args) {uploadclient 클라이언트 = new UploadClient (); client.upload ( "src // 목요일 // aslisttest.java"); } / *** 함수 : 파일을 서버에 업로드* 1. 서버에 연결을 설정* 2. 출력 스트림을 가져옵니다* 3. 파일 내용을 출력 스트림에 쓰기* 4. 서버의 응답 가져 오기* / private void upload (문자열 이름) {Socket Socket = null; 출력 스트림 아웃; try {socket = new Socket ( "127.0.0.1", 5555); out = socket.getOutputStream (); write2outputStream (이름, out); // 예외 캡처} catch (unknownHostException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); }} @test public void testupload () {upload ( "src // status.xml"); } / ** * 함수 : 파일 이름과 출력 스트림을 전달하고 파일을 출력 스트림에 쓰기 * @param path * @throws ioException * / private void write2outputStream (String Path, OutputStream Out) IoException {fileInputStream fis = null; 바이트 [] buf = 새로운 바이트 [1024]; 문자열 filename = ""; // 비즈니스 로직 시도 {// 1. 파일 이름 FILENAME = PATH.SUBSTRING (PATH.LASTINDEXOF ( '//')+1); System.out.println ( "업로드 할 파일 이름은 다음과 같습니다."+filename); out.write (filename.getBytes ()); out.write ( '/n'); // 2. 파일 내용을 작성합니다. fis = new FileInputStream (Path); int len; while ((len = fis.read (buf))! = -1) {out.write (buf, 0, len); } out.flush (); // 예외 처리} catch (ioException e) {e.printstacktrace (); // 자원을 닫습니다} 마지막으로 {fis.close (); out.close (); }} // upload @test 공개 void testwrite2outputstream ()가 ioexception {bytearrayoutputstream out = null; try {out = new BytearRayoutputStream (); write2outputStream ( "src // status.xml", out); System.out.println (out.toString ( "UTF-8")); } catch (ioexception e) {e.printstacktrace (); } 마침내 {out.close (); }}}이 기사는 "Java 업로드 작업 기술의 요약"으로 편집되었으며 모든 사람들은 배우고 읽을 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.