您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在java中使用socket對zip文件進行傳輸,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
服務器端程序:
import java.io.*; import java.net.*; import java.io.BufferedInputStream; public class SocketServer { ServerSocket ss=null; Socket s=null; DataInputStream inStream=null; DataOutputStream outStream=null; FileInputStream fin = null; public SocketServer() { try{ ss=new ServerSocket(765); s.setSoTimeout(3000); }catch(Exception e){ System.out.println(e.toString()); } } void waitForClient(){ try{ while(true){ s=ss.accept(); ThreadServer thread = new ThreadServer(s); thread.start(); } }catch(Exception e){ System.out.println(e.toString()); } } public static void main(String[] args) { SocketServer socketServer1 = new SocketServer(); socketServer1.waitForClient(); } }
線程類:
import java.io.*; import java.net.*; class ThreadServer extends Thread{ private Socket socket; private DataInputStream inStream=null; private DataOutputStream outStream=null; private FileInputStream fin = null; public ThreadServer(Socket sock){ this.socket = sock; } public void run(){ boolean bool = false; //while(!bool){ try{ inStream=new DataInputStream(socket.getInputStream()); outStream=new DataOutputStream(socket.getOutputStream()); fin = new FileInputStream("C:/temp/socket/200212060001_ds.zip"); //socket.setSoTimeout(3000); byte[] b = new byte[200]; int i; while((i=fin.read(b))!=-1){ outStream.write(b); } fin.close(); socket.close(); //bool = true; }catch(IOException ex){ System.out.println(ex); } //} } }
客戶端:
import java.net.*; import java.io.*; public class SocketClient{ Socket s=null; DataInputStream inStream=null; DataOutputStream outStream=null; FileOutputStream fout = null; public SocketClient() { try{ s=new Socket("192.9.207.52",765); //把這里的IP改成你運行SocketServer.class的IP inStream=new DataInputStream(s.getInputStream()); outStream=new DataOutputStream(s.getOutputStream()); fout = new FileOutputStream("C:/temp/socket/test11.zip"); s.setSoTimeout(3000); waitData(); } catch(Exception e){ System.out.println(e.toString()); } } void init() throws Exception{ } void waitData(){ try{ byte[] b = new byte[200]; int i; while((i=inStream.read(b))!=-1){ fout.write(b); } fout.flush(); fout.close(); s.close(); }catch(Exception e){ System.out.println(e.toString()); } } public static void main(String[] args) { SocketClient socketClient1 = new SocketClient(); } }
看完上述內容,你們對如何在java中使用socket對zip文件進行傳輸有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。