Tcp实现文件上传
package com.wuming.lesson02;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class TcpServerDemo02 {public static void main(String[] args) throws Exception {//1.創(chuàng)服務(wù)ServerSocket serverSocket = new ServerSocket(9000);//2.監(jiān)聽客戶端連接Socket socket = serverSocket.accept();//阻塞式監(jiān)聽,一直等待客戶端連接//3.獲取輸入流InputStream is = socket.getInputStream();//4.文件輸出FileOutputStream fos = new FileOutputStream(new File("receive2.jpg"));//自動(dòng)生成圖片byte[] buffer = new byte[1024];int len;while((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}//通知客戶端我接受完畢了OutputStream os = socket.getOutputStream();os.write("我接受完畢了,你可以斷開了".getBytes());//關(guān)閉資源fos.close();is.close();socket.close();serverSocket.close();}
}
===========================
package com.wuming.lesson02;import java.io.*;
import java.net.InetAddress;
import java.net.Socket;public class TcpClientDemo02 {public static void main(String[] args) throws Exception {//1.創(chuàng)Socket連接Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);//2.創(chuàng)輸出流OutputStream os = socket.getOutputStream();//3.讀取文件FileInputStream fis = new FileInputStream(new File("wg.jpg"));//圖片放入src同級(jí)路徑//4.寫文件byte[] buffer = new byte[1024];int len;while((len=fis.read(buffer))!=-1){os.write(buffer,0,len);}//通知服務(wù)器,我已經(jīng)結(jié)束了socket.shutdownOutput();//我已經(jīng)傳輸完了//確定服務(wù)器接受完畢,才斷開InputStream inputStream = socket.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer2 = new byte[1024];int len2;while((len2=inputStream.read(buffer2))!=-1){baos.write(buffer2,0,len2);}System.out.println(baos.toString());//5.關(guān)閉資源baos.close();inputStream.close();fis.close();os.close();socket.close();}
}
=================
先啟動(dòng)服務(wù)端,在啟動(dòng)客戶端,控制臺(tái)輸出:
在src同級(jí)路徑生成一個(gè)圖片
?
?
總結(jié)
- 上一篇: C语言 数组遍历 - C语言零基础入门教
- 下一篇: jq之animate()队列