新手學習-網路程式設計之TCP傳輸檔案

網路程式設計之TCP傳輸檔案

新手學習-網路程式設計之TCP傳輸檔案

上一篇《網路程式設計之TCP實現聊天》已經簡單介紹了TCP的概念及三次握手、四次揮手的通俗理解方式,這裡不再贅述,僅展示Java網路程式設計中的使用TCP協議實現傳輸檔案。

程式碼中:

“D:\\Program Files\\ideaIU\\IdeaWorkspace\\網路程式設計\\girl。jpg” //即將被傳輸的檔案的絕對路徑

“received。jpg” //接收到檔案時將其命名為這個名稱

完整原始碼如下:

客戶端

package tcp;

import java。io。*;

import java。net。InetAddress;

import java。net。Socket;

public class FilesClient {

public static void main(String[] args) throws Exception {

//建立Socket連線

InetAddress byName = InetAddress。getByName(“127。0。0。1”);

int port = 9000;

Socket socket = new Socket(byName,port);

//建立輸出流

OutputStream outputStream = socket。getOutputStream();

//讀取檔案

FileInputStream fileInputStream = new FileInputStream(new File(“D:\\Program Files\\ideaIU\\IdeaWorkspace\\網路程式設計\\girl。jpg”));

//寫出檔案

byte[] buffer = new byte[2014];

int length;

while ((length=fileInputStream。read(buffer))!=-1){

outputStream。write(buffer,0,length);

}

//告訴伺服器已經結束

socket。shutdownOutput();

//確定伺服器接收完畢 才能斷開連線

InputStream inputStream = socket。getInputStream();

//伺服器發過來的是Byte[]

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

byte[] bytes = new byte[2014];

int len;

while ((len=inputStream。read(bytes))!=-1){

byteArrayOutputStream。write(bytes,0,len);

}

System。out。println(byteArrayOutputStream。toString());

//關閉資源

byteArrayOutputStream。close();

inputStream。close();

fileInputStream。close();

outputStream。close();

socket。close();

}

}

服務端

package tcp;

import java。io。*;

import java。net。ServerSocket;

import java。net。Socket;

public class FilesServer {

public static void main(String[] args) throws Exception {

//建立服務

ServerSocket serverSocket = new ServerSocket(9000);

//監聽客戶端的連線

Socket accept = serverSocket。accept(); //阻塞式監聽,會一直等待客戶端的連線

//獲取輸入流

InputStream inputStream = accept。getInputStream();

//檔案輸出

FileOutputStream fileOutputStream = new FileOutputStream(new File(“received。jpg”));

int len;

byte[] bytes = new byte[2014];

while ((len=inputStream。read(bytes))!=-1){

fileOutputStream。write(bytes,0,len);

}

//通知客戶端接收完畢了

OutputStream outputStream = accept。getOutputStream();

outputStream。write(“我結束了,你可以斷開了!”。getBytes());

//關閉資源

fileOutputStream。close();

inputStream。close();

accept。close();

serverSocket。close();

}

}