Android基礎入門教程——7.6.3 基於TCP協議的Socket通訊(2)
本節引言:
上節中我們給大家接觸了Socket的一些基本概念以及使用方法,然後寫了一個小豬簡易聊天室的
Demo,相信大家對Socket有了初步的掌握,本節我們來學習下使用Socket來實現大檔案的斷點續傳!
這裡講解的是別人寫好的一個Socket上傳大檔案的例子,不要求我們自己可以寫出來,需要的時候會用
就好!
1.運行:
1.先把我們編寫好的Socket服務端運行起來:
2.將一個音頻檔案放到SD卡根目錄下:
3.運行我們的用戶端:
4.上傳成功後可以看到我們的服務端的項目下產生一個file的檔案夾,我們可以在這裡找到上傳的檔案:
.log那個是我們的記錄檔
2.實現流程圖:
3.程式碼範例:
先編寫一個服務端和用戶端都會用到的流解析類:
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 '': break loop; case '': int c2 = in.read(); if ((c2 != '') && (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 位元組數組 * @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(); }}
1)服務端的實現:
socket管理與多線程管理類:
FileServer.java:
public class FileServer { private ExecutorService executorService;//線程池 private int port;//監聽連接埠 private boolean quit = false;//退出 private ServerSocket server; private Map datas = new HashMap();//存放斷點資料 public FileServer(int port){ this.port = port; //建立線程池,池中具有(cpu個數*50)條線程 executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50); } /** * 退出 */ public void quit(){ this.quit = true; try { server.close(); } catch (IOException e) { } } /** * 啟動服務 * @throws Exception */ public void start() throws Exception{ server = new ServerSocket(port); while(!quit){ try { Socket socket = server.accept(); //為支援多使用者並發訪問,採用線程池管理每一個使用者的串連請求 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()); //得到用戶端發來的第一行協議資料:Content-Length=143253434;filename=xxx.3gp;sourceid= //如果使用者初次上傳檔案,sourceid的值為空白。 String head = StreamTool.readLine(inStream); System.out.println(head); if(head!=null){ //下面從協議資料中提取各項參數值 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();//生產資源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()){//如果上傳的檔案發生重名,然後進行改名 filename = filename.substring(0, filename.indexOf(.)-1)+ dir.listFiles().length+ filename.substring(filename.indexOf(.)); file = new File(dir, filename); } save(id, file); }else{// 如果存在上傳記錄,讀取已經上傳的資料長度 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));//讀取已經上傳的資料長度 } } } OutputStream outStream = socket.getOutputStream(); String response = sourceid=+ id+ ;position=+ position+ ; //伺服器收到用戶端的請求資訊後,給用戶端返迴響應資訊:sourceid=1274773833264;position=0 //sourceid由伺服器端產生,唯一標識上傳的檔案,position指示用戶端從檔案的什麼位置開始上傳 outStream.write(response.getBytes()); RandomAccessFile fileOutStream = new RandomAccessFile(file, rwd); if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//設定檔案長度 fileOutStream.seek(position);//指定從檔案的特定位置開始寫入資料 byte[] buffer = new byte[1024]; int len = -1; int length = position; while( (len=inStream.read(buffer)) != -1){//從輸入資料流中讀取資料寫入到檔案中 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);//即時記錄已經接收的檔案長度 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){ //日後可以改成通過資料庫存放 datas.put(id, new FileLog(id, saveFile.getAbsolutePath())); } //當檔案上傳完畢,刪除記錄 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; } } }
服務端介面類: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(伺服器已經啟動); 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(檔案上傳服務端: + address.getHostAddress()); window.setSize(400, 300); window.setVisible(true); }}
2)用戶端(Android端)
首先是布局檔案:activity_main.xml:
因為斷點續傳,我們需要儲存上傳的進度,我們需要用到資料庫,這裡我們定義一個資料庫
管理類: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) { }}
然後是資料庫操作類: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()}); }}
對了,別忘了用戶端也要貼上那個流解析類哦,最後就是我們的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 : ) + ; 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) {//如果是第一次上傳檔案,在資料庫中不存在該檔案所綁定的資源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;//累加已經上傳的資料長度 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中寫入這些許可權哦!
4.代碼下載:
Socket上傳大檔案demo
5.本節小結:
本節給大家介紹了基於TCP協議的Socket的另一個執行個體:使用Socket完成大檔案的續傳,
相信大家對Socket的瞭解更進一步,嗯,下一節再寫一個例子吧,兩個處於同一Wifi
下的手機相互傳遞資料的執行個體吧!就說這麼多,謝謝~