上節(jié)中我們給大家接觸了Socket的一些基本概念以及使用方法,然后寫了一個(gè)小豬簡(jiǎn)易聊天室的 Demo,相信大家對(duì)Socket有了初步的掌握,本節(jié)我們來(lái)學(xué)習(xí)下使用Socket來(lái)實(shí)現(xiàn)大文件的斷點(diǎn)續(xù)傳! 這里講解的是別人寫好的一個(gè)Socket上傳大文件的例子,不要求我們自己可以寫出來(lái),需要的時(shí)候會(huì)用 就好!
1.先把我們編寫好的Socket服務(wù)端運(yùn)行起來(lái):
2.將一個(gè)音頻文件放到SD卡根目錄下:
3.運(yùn)行我們的客戶端:
4.上傳成功后可以看到我們的服務(wù)端的項(xiàng)目下生成一個(gè)file的文件夾,我們可以在這里找到上傳的文件: .log那個(gè)是我們的日志文件
先編寫一個(gè)服務(wù)端和客戶端都會(huì)用到的流解析類:
StreamTool.java:
public class StreamTool { public static void save(File file, byte[] data) throws Exception { FileOutputStream outStream = new FileOutputStream(file); outStream.write(data); outStream.close(); } public static String readLine(PushbackInputStream in) throws IOException { char buf[] = new char[128]; int room = buf.length; int offset = 0; int c; loop: while (true) { switch (c = in.read()) { case -1: case '\n': break loop; case '\r': int c2 = in.read(); if ((c2 != '\n') && (c2 != -1)) in.unread(c2); break loop; default: if (--room < 0) { char[] lineBuffer = buf; buf = new char[offset + 128]; room = buf.length - offset - 1; System.arraycopy(lineBuffer, 0, buf, 0, offset); } buf[offset++] = (char) c; break; } } if ((c == -1) && (offset == 0)) return null; return String.copyValueOf(buf, 0, offset); } /** * 讀取流 * @param inStream * @return 字節(jié)數(shù)組 * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while( (len=inStream.read(buffer)) != -1){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } }
socket管理與多線程管理類:
FileServer.java:
public class FileServer { private ExecutorService executorService;//線程池 private int port;//監(jiān)聽端口 private boolean quit = false;//退出 private ServerSocket server; private Map<Long, FileLog> datas = new HashMap<Long, FileLog>();//存放斷點(diǎn)數(shù)據(jù) public FileServer(int port){ this.port = port; //創(chuàng)建線程池,池中具有(cpu個(gè)數(shù)*50)條線程 executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50); } /** * 退出 */ public void quit(){ this.quit = true; try { server.close(); } catch (IOException e) { } } /** * 啟動(dòng)服務(wù) * @throws Exception */ public void start() throws Exception{ server = new ServerSocket(port); while(!quit){ try { Socket socket = server.accept(); //為支持多用戶并發(fā)訪問(wèn),采用線程池管理每一個(gè)用戶的連接請(qǐng)求 executorService.execute(new SocketTask(socket)); } catch (Exception e) { // e.printStackTrace(); } } } private final class SocketTask implements Runnable{ private Socket socket = null; public SocketTask(Socket socket) { this.socket = socket; } public void run() { try { System.out.println("accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort()); PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream()); //得到客戶端發(fā)來(lái)的第一行協(xié)議數(shù)據(jù):Content-Length=143253434;filename=xxx.3gp;sourceid= //如果用戶初次上傳文件,sourceid的值為空。 String head = StreamTool.readLine(inStream); System.out.println(head); if(head!=null){ //下面從協(xié)議數(shù)據(jù)中提取各項(xiàng)參數(shù)值 String[] items = head.split(";"); String filelength = items[0].substring(items[0].indexOf("=")+1); String filename = items[1].substring(items[1].indexOf("=")+1); String sourceid = items[2].substring(items[2].indexOf("=")+1); long id = System.currentTimeMillis();//生產(chǎn)資源id,如果需要唯一性,可以采用UUID FileLog log = null; if(sourceid!=null && !"".equals(sourceid)){ id = Long.valueOf(sourceid); log = find(id);//查找上傳的文件是否存在上傳記錄 } File file = null; int position = 0; if(log==null){//如果不存在上傳記錄,為文件添加跟蹤記錄 String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date()); File dir = new File("file/"+ path); if(!dir.exists()) dir.mkdirs(); file = new File(dir, filename); if(file.exists()){//如果上傳的文件發(fā)生重名,然后進(jìn)行改名 filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf(".")); file = new File(dir, filename); } save(id, file); }else{// 如果存在上傳記錄,讀取已經(jīng)上傳的數(shù)據(jù)長(zhǎng)度 file = new File(log.getPath());//從上傳記錄中得到文件的路徑 if(file.exists()){ File logFile = new File(file.getParentFile(), file.getName()+".log"); if(logFile.exists()){ Properties properties = new Properties(); properties.load(new FileInputStream(logFile)); position = Integer.valueOf(properties.getProperty("length"));//讀取已經(jīng)上傳的數(shù)據(jù)長(zhǎng)度 } } } OutputStream outStream = socket.getOutputStream(); String response = "sourceid="+ id+ ";position="+ position+ "\r\n"; //服務(wù)器收到客戶端的請(qǐng)求信息后,給客戶端返回響應(yīng)信息:sourceid=1274773833264;position=0 //sourceid由服務(wù)器端生成,唯一標(biāo)識(shí)上傳的文件,position指示客戶端從文件的什么位置開始上傳 outStream.write(response.getBytes()); RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd"); if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//設(shè)置文件長(zhǎng)度 fileOutStream.seek(position);//指定從文件的特定位置開始寫入數(shù)據(jù) byte[] buffer = new byte[1024]; int len = -1; int length = position; while( (len=inStream.read(buffer)) != -1){//從輸入流中讀取數(shù)據(jù)寫入到文件中 fileOutStream.write(buffer, 0, len); length += len; Properties properties = new Properties(); properties.put("length", String.valueOf(length)); FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log")); properties.store(logFile, null);//實(shí)時(shí)記錄已經(jīng)接收的文件長(zhǎng)度 logFile.close(); } if(length==fileOutStream.length()) delete(id); fileOutStream.close(); inStream.close(); outStream.close(); file = null; } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(socket!=null && !socket.isClosed()) socket.close(); } catch (IOException e) {} } } } public FileLog find(Long sourceid){ return datas.get(sourceid); } //保存上傳記錄 public void save(Long id, File saveFile){ //日后可以改成通過(guò)數(shù)據(jù)庫(kù)存放 datas.put(id, new FileLog(id, saveFile.getAbsolutePath())); } //當(dāng)文件上傳完畢,刪除記錄 public void delete(long sourceid){ if(datas.containsKey(sourceid)) datas.remove(sourceid); } private class FileLog{ private Long id; private String path; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public FileLog(Long id, String path) { this.id = id; this.path = path; } } }
服務(wù)端界面類:ServerWindow.java:
public class ServerWindow extends Frame { private FileServer s = new FileServer(12345); private Label label; public ServerWindow(String title) { super(title); label = new Label(); add(label, BorderLayout.PAGE_START); label.setText("服務(wù)器已經(jīng)啟動(dòng)"); this.addWindowListener(new WindowListener() { public void windowOpened(WindowEvent e) { new Thread(new Runnable() { public void run() { try { s.start(); } catch (Exception e) { // e.printStackTrace(); } } }).start(); } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { s.quit(); System.exit(0); } public void windowClosed(WindowEvent e) { } public void windowActivated(WindowEvent e) { } }); } /** * @param args */ public static void main(String[] args) throws IOException { InetAddress address = InetAddress.getLocalHost(); ServerWindow window = new ServerWindow("文件上傳服務(wù)端:" + address.getHostAddress()); window.setSize(400, 300); window.setVisible(true); } }
首先是布局文件:activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="文件名" android:textSize="18sp" /> <EditText android:id="@+id/edit_fname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Nikki Jamal - Priceless.mp3" /> <Button android:id="@+id/btn_upload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上傳" /> <Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止" /> <ProgressBar android:id="@+id/pgbar" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="fill_parent" android:layout_height="40px" /> <TextView android:id="@+id/txt_result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" /> </LinearLayout>
因?yàn)閿帱c(diǎn)續(xù)傳,我們需要保存上傳的進(jìn)度,我們需要用到數(shù)據(jù)庫(kù),這里我們定義一個(gè)數(shù)據(jù)庫(kù) 管理類:DBOpenHelper.java::
/** * Created by Jay on 2015/9/17 0017. */ public class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context) { super(context, "jay.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
然后是數(shù)據(jù)庫(kù)操作類:UploadHelper.java:
/** * Created by Jay on 2015/9/17 0017. */ public class UploadHelper { private DBOpenHelper dbOpenHelper; public UploadHelper(Context context) { dbOpenHelper = new DBOpenHelper(context); } public String getBindId(File file) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select sourceid from uploadlog where path=?", new String[]{file.getAbsolutePath()}); if (cursor.moveToFirst()) { return cursor.getString(0); } return null; } public void save(String sourceid, File file) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("insert into uploadlog(path,sourceid) values(?,?)", new Object[]{file.getAbsolutePath(), sourceid}); } public void delete(File file) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from uploadlog where path=?", new Object[]{file.getAbsolutePath()}); } }
對(duì)了,別忘了客戶端也要貼上那個(gè)流解析類哦,最后就是我們的MainActivity.java了:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText edit_fname; private Button btn_upload; private Button btn_stop; private ProgressBar pgbar; private TextView txt_result; private UploadHelper upHelper; private boolean flag = true; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { pgbar.setProgress(msg.getData().getInt("length")); float num = (float) pgbar.getProgress() / (float) pgbar.getMax(); int result = (int) (num * 100); txt_result.setText(result + "%"); if (pgbar.getProgress() == pgbar.getMax()) { Toast.makeText(MainActivity.this, "上傳成功", Toast.LENGTH_SHORT).show(); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindViews(); upHelper = new UploadHelper(this); } private void bindViews() { edit_fname = (EditText) findViewById(R.id.edit_fname); btn_upload = (Button) findViewById(R.id.btn_upload); btn_stop = (Button) findViewById(R.id.btn_stop); pgbar = (ProgressBar) findViewById(R.id.pgbar); txt_result = (TextView) findViewById(R.id.txt_result); btn_upload.setOnClickListener(this); btn_stop.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_upload: String filename = edit_fname.getText().toString(); flag = true; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File file = new File(Environment.getExternalStorageDirectory(), filename); if (file.exists()) { pgbar.setMax((int) file.length()); uploadFile(file); } else { Toast.makeText(MainActivity.this, "文件并不存在~", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "SD卡不存在或者不可用", Toast.LENGTH_SHORT).show(); } break; case R.id.btn_stop: flag = false; break; } } private void uploadFile(final File file) { new Thread(new Runnable() { public void run() { try { String sourceid = upHelper.getBindId(file); Socket socket = new Socket("172.16.2.54", 12345); OutputStream outStream = socket.getOutputStream(); String head = "Content-Length=" + file.length() + ";filename=" + file.getName() + ";sourceid=" + (sourceid != null ? sourceid : "") + "\r\n"; outStream.write(head.getBytes()); PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream()); String response = StreamTool.readLine(inStream); String[] items = response.split(";"); String responseSourceid = items[0].substring(items[0].indexOf("=") + 1); String position = items[1].substring(items[1].indexOf("=") + 1); if (sourceid == null) {//如果是第一次上傳文件,在數(shù)據(jù)庫(kù)中不存在該文件所綁定的資源id upHelper.save(responseSourceid, file); } RandomAccessFile fileOutStream = new RandomAccessFile(file, "r"); fileOutStream.seek(Integer.valueOf(position)); byte[] buffer = new byte[1024]; int len = -1; int length = Integer.valueOf(position); while (flag && (len = fileOutStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); length += len;//累加已經(jīng)上傳的數(shù)據(jù)長(zhǎng)度 Message msg = new Message(); msg.getData().putInt("length", length); handler.sendMessage(msg); } if (length == file.length()) upHelper.delete(file); fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); } catch (Exception e) { Toast.makeText(MainActivity.this, "上傳異常~", Toast.LENGTH_SHORT).show(); } } }).start(); } }
最后,還有,記得往**AndroidManifest.xml**中寫入這些權(quán)限哦!
<!-- 在SDCard中創(chuàng)建與刪除文件權(quán)限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往SDCard寫入數(shù)據(jù)權(quán)限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- 訪問(wèn)internet權(quán)限 --> <uses-permission android:name="android.permission.INTERNET"/>
本節(jié)給大家介紹了基于TCP協(xié)議的Socket的另一個(gè)實(shí)例:使用Socket完成大文件的續(xù)傳, 相信大家對(duì)Socket的了解更進(jìn)一步,嗯,下一節(jié)再寫一個(gè)例子吧,兩個(gè)處于同一Wifi 下的手機(jī)相互傳遞數(shù)據(jù)的實(shí)例吧!就說(shuō)這么多,謝謝~
更多建議: