基於socket的上傳下載(Java)精簡版

snake_hand發表於2013-04-01

很簡單的一個例子,沒有介面只有程式碼。

伺服器端程式碼

package server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class AndroidServer implements Runnable {
	private ServerSocket serverSocket = null;
	private DataInputStream is;

	public void run() {
		if (serverSocket == null) {
			try {
				serverSocket = new ServerSocket(5926);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			Socket socket = serverSocket.accept();
			is = new DataInputStream(new BufferedInputStream(new FileInputStream("D:\\test.mp4"))); // 把需要上傳的檔案,放入InputStream
			DataOutputStream os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); // 初始化socket的OutputStream
			int count;
			byte[] buffer = new byte[1024];
			while ((count = is.read(buffer, 0, buffer.length)) != -1) { // 把檔案放入socket的OutputStream中
				os.write(buffer, 0, count);
			}
			os.flush();
			serverSocket.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Thread desktopServerThread = new Thread(new AndroidServer()); // 啟動服務
		desktopServerThread.start();
	}
}

客戶端程式碼

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;

public class test {

	public static void main(String[] args) {
		try {
			Socket socket = new Socket("192.168.0.228", 5926);
			DataInputStream dis = new DataInputStream(socket.getInputStream()); // 獲取socket中的InputStream
			DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("D:\\fuck")))); // 初始化OutputStream
			int count = 0;
			byte[] buffer = new byte[1024];
			while ((count = dis.read(buffer)) != -1) { // 把socket中的InputStream放入OutputStream
				os.write(buffer, 0, count);
			}
			os.close();
			socket.close(); // 上傳完成,關閉socket
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}

 

相關文章