TCP實現(xiàn)文件傳輸?shù)拇a
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/*
?* 上傳文件
?* 創(chuàng)建客戶端
?* 1.使用Socket創(chuàng)建客戶端(這里實際上就是和服務(wù)器建立連接)
?* 所以需要指定服務(wù)器的地址和端口
?* 2.輸入輸出流操作
?* 3.釋放資源
?*/
public class FileClient {
?? ?public static void main(String[] args) throws UnknownHostException, IOException {
?? ??? ?System.out.println("------client----------");
?? ??? ?//1.使用Socket創(chuàng)建客戶端(這里實際上就是和服務(wù)器建立連接)
?? ??? ?Socket client=new Socket("localhost",8888);
?? ??? ?// 2.文件的拷貝?? 文件上傳到服務(wù)器
?? ??? ?InputStream is=new BufferedInputStream(new FileInputStream("src/OIP.jpg"));
?? ??? ?OutputStream os=new BufferedOutputStream(client.getOutputStream());//獲取到圖片
?? ??? ?byte[]? flush=new byte[1024];
?? ??? ?int len=-1;
?? ??? ?while((len=is.read(flush))!=-1) {
?? ??? ??? ?os.write(flush,0,len);
?? ??? ?}
?? ??? ?os.flush();
?? ??? ?//3.釋放資源
?? ??? ?os.close();
?? ??? ?is.close();
?? ??? ?client.close();
?? ?}
}
package cn.jd.tcp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
?* 存儲文件
?* 創(chuàng)建服務(wù)器
?* 1.指定端口:使用ServerSocket創(chuàng)建服務(wù)器
?* 2.阻塞式的等待連接
?* 3.輸入輸出流操作
?* 4.釋放資源
?*/
public class FileServer {
?? ?public static void main(String[] args) throws IOException {
?? ??? ?System.out.println("------server----------");
?? ??? ?//1.指定端口:使用ServerSocket創(chuàng)建服務(wù)器
?? ??? ?ServerSocket server=new ServerSocket(8888);
?? ??? ?//2.阻塞式等待連接accept
?? ??? ?Socket client=server.accept();//一次accept就是一個連接
?? ??? ?System.out.println("一個客戶端建立了連接");
?? ??? ?//3.操作:文件拷貝?? 服務(wù)器將文件存儲到本地
?? ??? ?InputStream is=new BufferedInputStream(client.getInputStream());
?? ??? ?OutputStream os=new BufferedOutputStream(new FileOutputStream("src/tcp.jpg"));
?? ??? ?byte[]? flush=new byte[1024];
?? ??? ?int len=-1;
?? ??? ?while((len=is.read(flush))!=-1) {
?? ??? ??? ?os.write(flush,0,len);
?? ??? ?}
?? ??? ?os.flush();
?? ??? ?//4.釋放資源
?? ??? ?os.close();
?? ??? ?is.close();
?? ??? ?client.close();
?? ??? ?server.close();
?? ?}
?? ?
}
標(biāo)簽: