Java網路程式設計例子2_TCP檔案上傳
注意:網路程式設計的正常步驟先跑服務端,再跑客戶端; 第一步先用eclipse執行server端;
第二步用命令列執行客戶端;
檢視結果:
把檔案copy出去改下字尾,發現檔案可以開啟
package cn.njit.internet.fileUpload;
import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket;
/*******
- 檔案上傳
- TCP實現-服務端
- @author Administrator
*/ public class Server {
public static void main(String[] args) throws IOException {
int port=9999;
ServerSocket ss=new ServerSocket(port);
Socket cs=ss.accept();
ServerThread st=new ServerThread(cs);
st.start();
}
}
class ServerThread extends Thread{ Socket socket; String fileName; int i=(int) (Math.random()*10000000+1000000); public ServerThread(Socket socket) { this.socket=socket; this.fileName=String.valueOf(i); } public void run() { doFileUpload(); } private void doFileUpload() {
try { InputStream is=socket.getInputStream(); BufferedInputStream bis=new BufferedInputStream(is); byte[] buf=new byte[1024]; int len=bis.read(buf); fileName="D:\\First\\Second\\"+fileName; //實現斷點續傳 while(-1!=len) { FileOutputStream fos=new FileOutputStream(fileName,true); fos.write(buf,0,len); fos.close(); len=bis.read(buf); } /* FileOutputStream fos=new FileOutputStream(fileName,true); * while(-1!=len) { fos.write(buf,0,len); len=bis.read(buf); } fos.close(); */ bis.close(); } catch (IOException e) { System.out.println(e.getMessage()); } }
}
package cn.njit.internet.fileUpload;
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket;
/*******
- 檔案上傳
- TCP實現-客戶端
- @author Administrator
*/ public class Client {
public static void main(String[] args) throws Exception, IOException {
if(args.length<1) {
System.out.println("請輸入檔案路徑!");
return;
}
String fileName=args[0];
String serverHost="localhost";
int port =9999;
Socket socket=new Socket(serverHost,port);
OutputStream os=socket.getOutputStream();
InputStream is=new FileInputStream(fileName);
byte[] buf=new byte[1024];
int len=is.read(buf);
while(-1!=len) {
os.write(buf,0,len);
len=is.read(buf);
}
is.close();
os.close();
socket.close();
}
}
end; 2018.09.30;