1. android客户端

UploadActivity.javapackagecom.android.upload;importjava.io.File;importjava.io.OutputStream;importjava.io.PushbackInputStream;importjava.io.RandomAccessFile;importjava.net.Socket;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Environment;importandroid.os.Handler;importandroid.os.Message;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.ProgressBar;importandroid.widget.TextView;importandroid.widget.Toast;importcom.android.service.UploadLogService;importcom.android.socket.utils.StreamTool;publicclassUploadActivityextendsActivity{privateEditTextfilenameText;privateTextViewresulView;privateProgressBaruploadbar;privateUploadLogServicelogService;privatebooleanstart=true;privateHandlerhandler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){intlength=msg.getData().getInt("size");uploadbar.setProgress(length);floatnum=(float)uploadbar.getProgress()/(float)uploadbar.getMax();intresult=(int)(num*100);resulView.setText(result+"%");if(uploadbar.getProgress()==uploadbar.getMax()){Toast.makeText(UploadActivity.this,R.string.success,1).show();}}};@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);logService=newUploadLogService(this);filenameText=(EditText)this.findViewById(R.id.filename);uploadbar=(ProgressBar)this.findViewById(R.id.uploadbar);resulView=(TextView)this.findViewById(R.id.result);Buttonbutton=(Button)this.findViewById(R.id.button);Buttonbutton1=(Button)this.findViewById(R.id.stop);button1.setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){start=false;}});button.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){start=true;Stringfilename=filenameText.getText().toString();if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){FileuploadFile=newFile(Environment.getExternalStorageDirectory(),filename);if(uploadFile.exists()){uploadFile(uploadFile);}else{Toast.makeText(UploadActivity.this,R.string.filenotexsit,1).show();}}else{Toast.makeText(UploadActivity.this,R.string.sdcarderror,1).show();}}});}/***上传文件*@paramuploadFile*/privatevoiduploadFile(finalFileuploadFile){newThread(newRunnable(){@Overridepublicvoidrun(){try{uploadbar.setMax((int)uploadFile.length());Stringsouceid=logService.getBindId(uploadFile);Stringhead="Content-Length="+uploadFile.length()+";filename="+uploadFile.getName()+";sourceid="+(souceid==null?"":souceid)+"\r\n";Socketsocket=newSocket("192.168.1.78",7878);OutputStreamoutStream=socket.getOutputStream();outStream.write(head.getBytes());PushbackInputStreaminStream=newPushbackInputStream(socket.getInputStream());Stringresponse=StreamTool.readLine(inStream);String[]items=response.split(";");Stringresponseid=items[0].substring(items[0].indexOf("=")+1);Stringposition=items[1].substring(items[1].indexOf("=")+1);if(souceid==null){//代表原来没有上传过此文件,往数据库添加一条绑定记录logService.save(responseid,uploadFile);}RandomAccessFilefileOutStream=newRandomAccessFile(uploadFile,"r");fileOutStream.seek(Integer.valueOf(position));byte[]buffer=newbyte[1024];intlen=-1;intlength=Integer.valueOf(position);while(start&&(len=fileOutStream.read(buffer))!=-1){outStream.write(buffer,0,len);length+=len;Messagemsg=newMessage();msg.getData().putInt("size",length);handler.sendMessage(msg);}fileOutStream.close();outStream.close();inStream.close();socket.close();if(length==uploadFile.length())logService.delete(uploadFile);}catch(Exceptione){e.printStackTrace();}}}).start();}}StreamTool.javapackagecom.android.socket.utils;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.PushbackInputStream;publicclassStreamTool{publicstaticvoidsave(Filefile,byte[]data)throwsException{FileOutputStreamoutStream=newFileOutputStream(file);outStream.write(data);outStream.close();}publicstaticStringreadLine(PushbackInputStreamin)throwsIOException{charbuf[]=newchar[128];introom=buf.length;intoffset=0;intc;loop:while(true){switch(c=in.read()){case-1:case'\n':breakloop;case'\r':intc2=in.read();if((c2!='\n')&&(c2!=-1))in.unread(c2);breakloop;default:if(--room<0){char[]lineBuffer=buf;buf=newchar[offset+128];room=buf.length-offset-1;System.arraycopy(lineBuffer,0,buf,0,offset);}buf[offset++]=(char)c;break;}}if((c==-1)&&(offset==0))returnnull;returnString.copyValueOf(buf,0,offset);}/***读取流*@paraminStream*@return字节数组*@throwsException*/publicstaticbyte[]readStream(InputStreaminStream)throwsException{ByteArrayOutputStreamoutSteam=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intlen=-1;while((len=inStream.read(buffer))!=-1){outSteam.write(buffer,0,len);}outSteam.close();inStream.close();returnoutSteam.toByteArray();}}UploadLogService.javapackagecom.android.service;importjava.io.File;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;publicclassUploadLogService{privateDBOpenHelperdbOpenHelper;publicUploadLogService(Contextcontext){this.dbOpenHelper=newDBOpenHelper(context);}publicvoidsave(Stringsourceid,FileuploadFile){SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();db.execSQL("insertintouploadlog(uploadfilepath,sourceid)values(?,?)",newObject[]{uploadFile.getAbsolutePath(),sourceid});}publicvoiddelete(FileuploadFile){SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();db.execSQL("deletefromuploadlogwhereuploadfilepath=?",newObject[]{uploadFile.getAbsolutePath()});}publicStringgetBindId(FileuploadFile){SQLiteDatabasedb=dbOpenHelper.getReadableDatabase();Cursorcursor=db.rawQuery("selectsourceidfromuploadlogwhereuploadfilepath=?",newString[]{uploadFile.getAbsolutePath()});if(cursor.moveToFirst()){returncursor.getString(0);}returnnull;}}DBOpenHelper.javapackagecom.android.service;importandroid.content.Context;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;publicclassDBOpenHelperextendsSQLiteOpenHelper{publicDBOpenHelper(Contextcontext){super(context,"upload.db",null,1);}@OverridepublicvoidonCreate(SQLiteDatabasedb){db.execSQL("CREATETABLEuploadlog(_idintegerprimarykeyautoincrement,uploadfilepathvarchar(100),sourceidvarchar(10))");}@OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){db.execSQL("DROPTABLEIFEXISTSuploadlog");onCreate(db);}}main.xml<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/filename"/><EditTextandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="022.jpg"android:id="@+id/filename"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/button"android:id="@+id/button"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="暂停"android:id="@+id/stop"/><ProgressBarandroid:layout_width="fill_parent"android:layout_height="20px"style="?android:attr/progressBarStyleHorizontal"android:id="@+id/uploadbar"/><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center"android:id="@+id/result"/></LinearLayout>AndroidManifest.xml<?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.android.upload"android:versionCode="1"android:versionName="1.0"><uses-sdkandroid:minSdkVersion="8"/><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name"><activityandroid:name=".UploadActivity"android:label="@string/app_name"><intent-filter><actionandroid:name="android.intent.action.MAIN"/><categoryandroid:name="android.intent.category.LAUNCHER"/></intent-filter></activity></application><!--访问网络的权限--><uses-permissionandroid:name="android.permission.INTERNET"/><!--在SDCard中创建与删除文件权限--><uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><!--往SDCard写入数据权限--><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/></manifest>

2.服务端

SocketServer.javapackagecom.android.socket.server;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.io.PushbackInputStream;importjava.io.RandomAccessFile;importjava.net.ServerSocket;importjava.net.Socket;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.HashMap;importjava.util.Map;importjava.util.Properties;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importcom.android.socket.utils.StreamTool;publicclassSocketServer{privateStringuploadPath="D:/uploadFile/";privateExecutorServiceexecutorService;//线程池privateServerSocketss=null;privateintport;//监听端口privatebooleanquit;//是否退出privateMap<Long,FileLog>datas=newHashMap<Long,FileLog>();//存放断点数据,最好改为数据库存放publicSocketServer(intport){this.port=port;//初始化线程池executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*50);}//启动服务publicvoidstart()throwsException{ss=newServerSocket(port);while(!quit){Socketsocket=ss.accept();//接受客户端的请求//为支持多用户并发访问,采用线程池管理每一个用户的连接请求executorService.execute(newSocketTask(socket));//启动一个线程来处理请求}}//退出publicvoidquit(){this.quit=true;try{ss.close();}catch(IOExceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args)throwsException{SocketServerserver=newSocketServer(7878);server.start();}privateclassSocketTaskimplementsRunnable{privateSocketsocket;publicSocketTask(Socketsocket){this.socket=socket;}@Overridepublicvoidrun(){try{System.out.println("acceptedconnenctionfrom"+socket.getInetAddress()+"@"+socket.getPort());PushbackInputStreaminStream=newPushbackInputStream(socket.getInputStream());//得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=//如果用户初次上传文件,sourceid的值为空。Stringhead=StreamTool.readLine(inStream);System.out.println(head);if(head!=null){//下面从协议数据中读取各种参数值String[]items=head.split(";");Stringfilelength=items[0].substring(items[0].indexOf("=")+1);Stringfilename=items[1].substring(items[1].indexOf("=")+1);Stringsourceid=items[2].substring(items[2].indexOf("=")+1);Longid=System.currentTimeMillis();FileLoglog=null;if(null!=sourceid&&!"".equals(sourceid)){id=Long.valueOf(sourceid);log=find(id);//查找上传的文件是否存在上传记录}Filefile=null;intposition=0;if(log==null){//如果上传的文件不存在上传记录,为文件添加跟踪记录Stringpath=newSimpleDateFormat("yyyy/MM/dd/HH/mm").format(newDate());Filedir=newFile(uploadPath+path);if(!dir.exists())dir.mkdirs();file=newFile(dir,filename);if(file.exists()){//如果上传的文件发生重名,然后进行改名filename=filename.substring(0,filename.indexOf(".")-1)+dir.listFiles().length+filename.substring(filename.indexOf("."));file=newFile(dir,filename);}save(id,file);}else{//如果上传的文件存在上传记录,读取上次的断点位置file=newFile(log.getPath());//从上传记录中得到文件的路径if(file.exists()){FilelogFile=newFile(file.getParentFile(),file.getName()+".log");if(logFile.exists()){Propertiesproperties=newProperties();properties.load(newFileInputStream(logFile));position=Integer.valueOf(properties.getProperty("length"));//读取断点位置}}}OutputStreamoutStream=socket.getOutputStream();Stringresponse="sourceid="+id+";position="+position+"\r\n";//服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0//sourceid由服务生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传outStream.write(response.getBytes());RandomAccessFilefileOutStream=newRandomAccessFile(file,"rwd");if(position==0)fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度fileOutStream.seek(position);//移动文件指定的位置开始写入数据byte[]buffer=newbyte[1024];intlen=-1;intlength=position;while((len=inStream.read(buffer))!=-1){//从输入流中读取数据写入到文件中fileOutStream.write(buffer,0,len);length+=len;Propertiesproperties=newProperties();properties.put("length",String.valueOf(length));FileOutputStreamlogFile=newFileOutputStream(newFile(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(Exceptione){e.printStackTrace();}finally{try{if(socket!=null&&!socket.isClosed())socket.close();}catch(IOExceptione){}}}}publicFileLogfind(Longsourceid){returndatas.get(sourceid);}//保存上传记录publicvoidsave(Longid,FilesaveFile){//日后可以改成通过数据库存放datas.put(id,newFileLog(id,saveFile.getAbsolutePath()));}//当文件上传完毕,删除记录publicvoiddelete(longsourceid){if(datas.containsKey(sourceid))datas.remove(sourceid);}privateclassFileLog{privateLongid;privateStringpath;publicFileLog(Longid,Stringpath){super();this.id=id;this.path=path;}publicLonggetId(){returnid;}publicvoidsetId(Longid){this.id=id;}publicStringgetPath(){returnpath;}publicvoidsetPath(Stringpath){this.path=path;}}}ServerWindow.javapackagecom.android.socket.server;importjava.awt.BorderLayout;importjava.awt.Frame;importjava.awt.Label;importjava.awt.event.WindowEvent;importjava.awt.event.WindowListener;publicclassServerWindowextendsFrame{privateSocketServerserver;privateLabellabel;publicServerWindow(Stringtitle){super(title);server=newSocketServer(7878);label=newLabel();add(label,BorderLayout.PAGE_START);label.setText("服务器已经启动");this.addWindowListener(newWindowListener(){@OverridepublicvoidwindowOpened(WindowEvente){newThread(newRunnable(){@Overridepublicvoidrun(){try{server.start();}catch(Exceptione){e.printStackTrace();}}}).start();}@OverridepublicvoidwindowIconified(WindowEvente){}@OverridepublicvoidwindowDeiconified(WindowEvente){}@OverridepublicvoidwindowDeactivated(WindowEvente){}@OverridepublicvoidwindowClosing(WindowEvente){server.quit();System.exit(0);}@OverridepublicvoidwindowClosed(WindowEvente){}@OverridepublicvoidwindowActivated(WindowEvente){}});}/***@paramargs*/publicstaticvoidmain(String[]args){ServerWindowwindow=newServerWindow("文件上传服务端");window.setSize(300,300);window.setVisible(true);}}StreamTool.javapackagecom.android.socket.utils;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.PushbackInputStream;publicclassStreamTool{publicstaticvoidsave(Filefile,byte[]data)throwsException{FileOutputStreamoutStream=newFileOutputStream(file);outStream.write(data);outStream.close();}publicstaticStringreadLine(PushbackInputStreamin)throwsIOException{charbuf[]=newchar[128];introom=buf.length;intoffset=0;intc;loop:while(true){switch(c=in.read()){case-1:case'\n':breakloop;case'\r':intc2=in.read();if((c2!='\n')&&(c2!=-1))in.unread(c2);breakloop;default:if(--room<0){char[]lineBuffer=buf;buf=newchar[offset+128];room=buf.length-offset-1;System.arraycopy(lineBuffer,0,buf,0,offset);}buf[offset++]=(char)c;break;}}if((c==-1)&&(offset==0))returnnull;returnString.copyValueOf(buf,0,offset);}/***读取流*@paraminStream*@return字节数组*@throwsException*/publicstaticbyte[]readStream(InputStreaminStream)throwsException{ByteArrayOutputStreamoutSteam=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intlen=-1;while((len=inStream.read(buffer))!=-1){outSteam.write(buffer,0,len);}outSteam.close();inStream.close();returnoutSteam.toByteArray();}}


更多相关文章

  1. Android 密度转换 java文件
  2. android用异步操作AsyncTask编写文件查看器
  3. 手动操作Android数据库
  4. Android 打开指定文件夹
  5. Android之数据库操作
  6. android解压ZIP文件
  7. android比较重要的三个img文件
  8. android之bundle传递数据--两个activities之间

随机推荐

  1. Android控件的一般属性
  2. 它们的定义android滑动菜单
  3. Android(安卓)4.0 新增的显示数据集的桌
  4. Android模拟机出现Installation failed d
  5. android bitmap内存溢出
  6. Android自定义控件实战——滚动选择器Pic
  7. 【Android】解决Fragment多层嵌套时onAct
  8. Android(安卓)APK反编译工具介绍
  9. Socket(TCP)
  10. RxJava 官方文档中文翻译