Android Socket 传输文件

效果:发送端用Socket发送指定路径的文件给接收端,接收端将文件存储到指定路径。


发送端的MainActivity.java

创建一个按钮,在按钮监听器中设置文件路径、文件名、IP地址以及端口号,然后开启一个线程执行SendFile()方法进行Socket文件发送。在SendFile()方法中,文件名和文件数据分别用name和data两个socket进行发送。

public class MainActivity extends Activity {

	private Button btnSend;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
											
				final String path = "/storage/emulated/0/qqmusic/song/A.mp3";
				final String fileName = "A.mp3";
				final String ipAddress = "192.168.1.143";
				final int port = 9999;

				Thread sendThread = new Thread(new Runnable() {
					@Override
					public void run() {
						SendFile(fileName, path, ipAddress, port);
					}
				});
				sendThread.start();
			}
		});
	}

	public String SendFile(String fileName, String path, String ipAddress, int port) {
		try {
			Socket name = new Socket(ipAddress, port);
			OutputStream outputName = name.getOutputStream();
			OutputStreamWriter outputWriter = new OutputStreamWriter(outputName);
			BufferedWriter bwName = new BufferedWriter(outputWriter);
			bwName.write(fileName);
			bwName.close();
			outputWriter.close();
			outputName.close();
			name.close();

			Socket data = new Socket(ipAddress, port);
			OutputStream outputData = data.getOutputStream();
			FileInputStream fileInput = new FileInputStream(path);
			int size = -1;
			byte[] buffer = new byte[1024];
			while ((size = fileInput.read(buffer, 0, 1024)) != -1) {
				outputData.write(buffer, 0, size);
			}
			outputData.close();
			fileInput.close();
			data.close();
			return fileName + " 发送完成";
		} catch (Exception e) {
			return "发送错误:\n" + e.getMessage();
		}
	}
}


接收端的MainActivity.java

在线程Listener中创建一个ServerSocket和Socket的对象,执行ReceiveFile()方法进行文件的接收。在ReceiveFile()方法中,由于发送端的SendFile方法使用两个socket分别发送文件名和文件数据,因此该方法也要两个socket,即name和data分别对文件名和文件数据进行接收。在socket data中需设置指定的文件存储路径。

public class MainActivity extends Activity {

	private ServerSocket server;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 服务器端用于监听Socket的线程
		Thread listener = new Thread(new Runnable() {
			@Override
			public void run() {

				int port = 9999;
				while (port > 9000) {
					try {
						server = new ServerSocket(port);
						break;
					} catch (Exception e) {
						port--;
					}
				}
				if (server != null) {
					while (true) {
						ReceiveFile();
					}
				}
			}
		});
		listener.start();
	}

	// 文件接收方法
	public String ReceiveFile() {
		try {
			// 接收文件名
			Socket name = server.accept();
			InputStream nameStream = name.getInputStream();
			InputStreamReader streamReader = new InputStreamReader(nameStream);
			BufferedReader br = new BufferedReader(streamReader);
			String fileName = br.readLine();
			br.close();
			streamReader.close();
			nameStream.close();
			name.close();

			// 接收文件数据
			Socket data = server.accept();
			InputStream dataStream = data.getInputStream();
			File dir = new File("/sdcard/MyMusic"); // 创建文件的存储路径
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String savePath = "/sdcard/MyMusic/" + fileName; // 定义完整的存储路径
			FileOutputStream file = new FileOutputStream(savePath, false);
			byte[] buffer = new byte[1024];
			int size = -1;
			while ((size = dataStream.read(buffer)) != -1) {
				file.write(buffer, 0, size);
			}
			file.close();
			dataStream.close();
			data.close();
			return fileName + " 接收完成";
		} catch (Exception e) {
			return "接收错误:\n" + e.getMessage();
		}
	}
}


发送端和接收端的Demo下载链接:http://download.csdn.net/detail/kylsen/9686394

你可能感兴趣的:(Android Socket 传输文件)