(1)tcp客戶端
public class upTcpClient {
public static void main(String[] args) throws IOException {
//1.利用本地IO流綁定待上傳文件
FileInputStream fis = new FileInputStream("c:\\1.jpg");
//2.創建網絡IO流,綁定上傳目的地及端口
Socket socket = new Socket("127.0.0.1", 8888);
//3.獲取網絡輸出流,該流可以將文件上傳到目的地
OutputStream os = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while((len=fis.read())!=-1){//4.讀取待上傳文件
os.write(bytes,0,len);//5.將讀取的byte上傳到目的地
}
socket.shutdownOutput();//6.防阻塞,當文件上傳結束後自動結束while循環
InputStream is = socket.getInputStream();//7.獲取網絡輸入流,用於讀取服務器返回信息
byte[] byte1 = new byte[1024];
is.read(byte1);//8.讀取返回信息,如果信息量較大,可以使用while循環讀取
System.out.println(new String(byte1));//9.打印服務器返回的消息內容
//關閉流對象
fis.close();
socket.close();
}
}
(2)服務器端
public class uploadTCPServer {
public static void main(String[] args) throws IOException {
//1.創建服務器監聽端口的套接字
ServerSocket ss = new ServerSocket(8888);
//2.判斷文件寫入的路徑是否存在,不存在則創建
File file = new File("C:\\upload");
if(!file.exists()){
file.mkdirs();
}
//3.使用死循環實現無間斷監聽(優化1)
while(true){
//4.判斷客戶端是否發送連接請求,與客戶端建立連接,並獲取Socket流
Socket socket = ss.accept();
//利用多線程實現服務器端併發處理上傳請求(優化2)
new Thread(()->{
//5.自定義文件名稱(優化3)
String fileName = "njau"+System.currentTimeMillis()+new Random().nextInt(999999)+".jpg";
//6.初始化本地IO流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file+"\\"+fileName);//綁定輸出路徑及文件名稱
InputStream is = socket.getInputStream();//7.獲取socket中的網絡輸入流,與客戶端socket相對應
int len=0;
byte[] bytes = new byte[1024];
while((len=is.read(bytes))!=-1){//8.利用socket中的讀入流的read方法,讀取上傳的內容
fos.write(bytes,0,len);//9.利用本地IO流將上傳內容寫入到對應的文件中
}
OutputStream os = socket.getOutputStream();//10.向客戶端回覆消息
os.write("已收到".getBytes());
fos.close();//關閉流對象
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
//ss.close();
}
}