基于socket的上传下载(Java)精简版
很简单的一个例子,没有界面只有代码。
服务器端代码
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 { } } }