PC客户端与Android服务端的Socket同步通信(USB)

需求:

1.一个android端的service后台运行的程序,作为socket的服务器端;用于接收Pc client端发来的命令,来处理数据后,把结果发给PC client

2.PC端程序,作为socket的客户端,用于给android手机端发操作命令

难点分析:

1.手机一定要有adb模式,即插上USB线时马上提示的对话框选adb。好多对手机的操作都可以用adb直接作。

不过,我发现LG GW880就没有,要去下载个

2.android默认手机端的IP为“127.0.0.1”

3.要想联通PC与android手机的sokcet,一定要用adb forward 来作下端口转发才能连上socket.

  1. Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");
  2. Thread.sleep(3000);

4.android端的service程序Install到手机上容易,但是还要有方法来从PC的client端来启动手机上的service ,这个办法可以通过PC端adb命令来发一个Broastcast,手机端再写个接收BroastcastReceive来接收这个Broastcast,在这个BroastcastReceive来启动service

pc端命令:

  1. Runtime.getRuntime().exec(
  2. "adbshellambroadcast-aNotifyServiceStart");

android端的代码:ServiceBroadcastReceiver.java

  1. packagecom.otheri.service;
  2. importandroid.content.BroadcastReceiver;
  3. importandroid.content.Context;
  4. importandroid.content.Intent;
  5. importandroid.util.Log;
  6. publicclassServiceBroadcastReceiverextendsBroadcastReceiver{
  7. privatestaticStringSTART_ACTION="NotifyServiceStart";
  8. privatestaticStringSTOP_ACTION="NotifyServiceStop";
  9. @Override
  10. publicvoidonReceive(Contextcontext,Intentintent){
  11. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  12. +"ServiceBroadcastReceiveronReceive");
  13. Stringaction=intent.getAction();
  14. if(START_ACTION.equalsIgnoreCase(action)){
  15. context.startService(newIntent(context,androidService.class));
  16. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  17. +"ServiceBroadcastReceiveronReceivestartend");
  18. }elseif(STOP_ACTION.equalsIgnoreCase(action)){
  19. context.stopService(newIntent(context,androidService.class));
  20. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  21. +"ServiceBroadcastReceiveronReceivestopend");
  22. }
  23. }
  24. }

5.由于是USB连接,所以socket就可以设计为一但连接就一直联通,即在new socket和开完out,in流后,就用个while(true){}来循环PC端和android端的读和写

android的代码:

  1. publicvoidrun(){
  2. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  3. +"aclienthasconnectedtoserver!");
  4. BufferedOutputStreamout;
  5. BufferedInputStreamin;
  6. try{
  7. /*PC端发来的数据msg*/
  8. StringcurrCMD="";
  9. out=newBufferedOutputStream(client.getOutputStream());
  10. in=newBufferedInputStream(client.getInputStream());
  11. //testSocket();//测试socket方法
  12. androidService.ioThreadFlag=true;
  13. while(androidService.ioThreadFlag){
  14. try{
  15. if(!client.isConnected()){
  16. break;
  17. }
  18. /*接收PC发来的数据*/
  19. Log.v(androidService.TAG,Thread.currentThread().getName()
  20. +"---->"+"willread......");
  21. /*读操作命令*/
  22. currCMD=readCMDFromSocket(in);
  23. Log.v(androidService.TAG,Thread.currentThread().getName()
  24. +"---->"+"**currCMD===="+currCMD);
  25. /*根据命令分别处理数据*/
  26. if(currCMD.equals("1")){
  27. out.write("OK".getBytes());
  28. out.flush();
  29. }elseif(currCMD.equals("2")){
  30. out.write("OK".getBytes());
  31. out.flush();
  32. }elseif(currCMD.equals("3")){
  33. out.write("OK".getBytes());
  34. out.flush();
  35. }elseif(currCMD.equals("4")){
  36. /*准备接收文件数据*/
  37. try{
  38. out.write("servicereceiveOK".getBytes());
  39. out.flush();
  40. }catch(IOExceptione){
  41. e.printStackTrace();
  42. }
  43. /*接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据*/
  44. byte[]filelength=newbyte[4];
  45. byte[]fileformat=newbyte[4];
  46. byte[]filebytes=null;
  47. /*从socket流中读取完整文件数据*/
  48. filebytes=receiveFileFromSocket(in,out,filelength,
  49. fileformat);
  50. //Log.v(Service139.TAG,"receivedata="+new
  51. //String(filebytes));
  52. try{
  53. /*生成文件*/
  54. Filefile=FileHelper.newFile("R0013340.JPG");
  55. FileHelper.writeFile(file,filebytes,0,
  56. filebytes.length);
  57. }catch(IOExceptione){
  58. e.printStackTrace();
  59. }
  60. }elseif(currCMD.equals("exit")){
  61. }
  62. }catch(Exceptione){
  63. //try{
  64. //out.write("error".getBytes("utf-8"));
  65. //out.flush();
  66. //}catch(IOExceptione1){
  67. //e1.printStackTrace();
  68. //}
  69. Log.e(androidService.TAG,Thread.currentThread().getName()
  70. +"---->"+"readwriteerror111111");
  71. }
  72. }
  73. out.close();
  74. in.close();
  75. }catch(Exceptione){
  76. Log.e(androidService.TAG,Thread.currentThread().getName()
  77. +"---->"+"readwriteerror222222");
  78. e.printStackTrace();
  79. }finally{
  80. try{
  81. if(client!=null){
  82. Log.v(androidService.TAG,Thread.currentThread().getName()
  83. +"---->"+"client.close()");
  84. client.close();
  85. }
  86. }catch(IOExceptione){
  87. Log.e(androidService.TAG,Thread.currentThread().getName()
  88. +"---->"+"readwriteerror333333");
  89. e.printStackTrace();
  90. }
  91. }

6.如果是在PC端和android端的读写操作来while(true){}循环,这样socket流的结尾不好判断,不能用“-1”来判断,因为“-1”是只有在socket关闭时才作为判断结尾。

7.socket在out.write(bytes);时,要是数据太大时,超过socket的缓存,socket自动分包发送,所以对方就一定要用循环来多次读。最好的办法就是服务器和客户端协议好,比如发文件时,先写过来一个要发送的文件的大小,然后再发送文件;对方用这个大小,来循环读取数据。

android端接收数据的代码:

  1. /**
  2. *功能:从socket流中读取完整文件数据
  3. *
  4. *InputStreamin:socket输入流
  5. *
  6. *byte[]filelength:流的前4个字节存储要转送的文件的字节数
  7. *
  8. *byte[]fileformat:流的前5-8字节存储要转送的文件的格式(如.apk)
  9. *
  10. **/
  11. publicstaticbyte[]receiveFileFromSocket(InputStreamin,
  12. OutputStreamout,byte[]filelength,byte[]fileformat){
  13. byte[]filebytes=null;//文件数据
  14. try{
  15. intfilelen=MyUtil.bytesToInt(filelength);//文件长度从4字节byte[]转成Int
  16. Stringstrtmp="readfilelengthok:"+filelen;
  17. out.write(strtmp.getBytes("utf-8"));
  18. out.flush();
  19. filebytes=newbyte[filelen];
  20. intpos=0;
  21. intrcvLen=0;
  22. while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){
  23. pos+=rcvLen;
  24. }
  25. Log.v(androidService.TAG,Thread.currentThread().getName()
  26. +"---->"+"readfileOK:filesize="+filebytes.length);
  27. out.write("readfileok".getBytes("utf-8"));
  28. out.flush();
  29. }catch(Exceptione){
  30. Log.v(androidService.TAG,Thread.currentThread().getName()
  31. +"---->"+"receiveFileFromSocketerror");
  32. e.printStackTrace();
  33. }
  34. returnfilebytes;
  35. }

8.socket的最重要的机制就是读写采用的是阻塞的方式,如果客户端作为命令发起者,服务器端作为接收者的话,只有当客户端client用out.writer()写到输出流里后,即流中有数据service的read才会执行,不然就会一直停在read()那里等数据。

9.还要让服务器端可以同时连接多个client,即服务器端用new thread()来作数据读取操作。

源码:

客户端(pc端):

PC客户端与Android服务端的Socket同步通信(USB)

testPcClient.java

  1. importjava.io.BufferedInputStream;
  2. importjava.io.BufferedOutputStream;
  3. importjava.io.BufferedReader;
  4. importjava.io.ByteArrayOutputStream;
  5. importjava.io.IOException;
  6. importjava.io.InputStream;
  7. importjava.io.InputStreamReader;
  8. importjava.net.InetAddress;
  9. importjava.net.Socket;
  10. importjava.net.UnknownHostException;
  11. publicclasstestPcClient{
  12. /**
  13. *@paramargs
  14. *@throwsInterruptedException
  15. */
  16. publicstaticvoidmain(String[]args)throwsInterruptedException{
  17. try{
  18. Runtime.getRuntime().exec(
  19. "adbshellambroadcast-aNotifyServiceStop");
  20. Thread.sleep(3000);
  21. Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");
  22. Thread.sleep(3000);
  23. Runtime.getRuntime().exec(
  24. "adbshellambroadcast-aNotifyServiceStart");
  25. Thread.sleep(3000);
  26. }catch(IOExceptione3){
  27. e3.printStackTrace();
  28. }
  29. Socketsocket=null;
  30. try{
  31. InetAddressserverAddr=null;
  32. serverAddr=InetAddress.getByName("127.0.0.1");
  33. System.out.println("TCP1111"+"C:Connecting...");
  34. socket=newSocket(serverAddr,12580);
  35. Stringstr="hi,wufenglong";
  36. System.out.println("TCP221122"+"C:RECEIVE");
  37. BufferedOutputStreamout=newBufferedOutputStream(socket
  38. .getOutputStream());
  39. BufferedInputStreamin=newBufferedInputStream(socket
  40. .getInputStream());
  41. BufferedReaderbr=newBufferedReader(newInputStreamReader(
  42. System.in));
  43. booleanflag=true;
  44. while(flag){
  45. System.out.print("请输入1~6的数字,退出输入exit:");
  46. StringstrWord=br.readLine();//从控制台输入1~6
  47. if(strWord.equals("1")){
  48. out.write("1".getBytes());
  49. out.flush();
  50. System.out.println("1finishsendingthedata");
  51. StringstrFormsocket=readFromSocket(in);
  52. System.out.println("thedatasentbyserveris:/r/n"
  53. +strFormsocket);
  54. System.out
  55. .println("=============================================");
  56. }elseif(strWord.equals("2")){
  57. out.write("2".getBytes());
  58. out.flush();
  59. System.out.println("2finishsendingthedata");
  60. StringstrFormsocket=readFromSocket(in);
  61. System.out.println("thedatasentbyserveris:/r/n"
  62. +strFormsocket);
  63. System.out
  64. .println("=============================================");
  65. }elseif(strWord.equals("3")){
  66. out.write("3".getBytes());
  67. out.flush();
  68. System.out.println("3finishsendingthedata");
  69. StringstrFormsocket=readFromSocket(in);
  70. System.out.println("thedatasentbyserveris:/r/n"
  71. +strFormsocket);
  72. System.out
  73. .println("=============================================");
  74. }elseif(strWord.equals("4")){
  75. /*发送命令*/
  76. out.write("4".getBytes());
  77. out.flush();
  78. System.out.println("sendfilefinishsendingtheCMD:");
  79. /*服务器反馈:准备接收*/
  80. StringstrFormsocket=readFromSocket(in);
  81. System.out
  82. .println("servicereadyreceicedata:UPDATE_CONTACTS:"
  83. +strFormsocket);
  84. byte[]filebytes=FileHelper.readFile("R0013340.JPG");
  85. System.out.println("filesize="+filebytes.length);
  86. /*将整数转成4字节byte数组*/
  87. byte[]filelength=newbyte[4];
  88. filelength=tools.intToByte(filebytes.length);
  89. /*将.apk字符串转成4字节byte数组*/
  90. byte[]fileformat=null;
  91. fileformat=".apk".getBytes();
  92. System.out
  93. .println("fileformatlength="+fileformat.length);
  94. /*字节流中前4字节为文件长度,4字节文件格式,以后是文件流*/
  95. /*注意如果write里的byte[]超过socket的缓存,系统自动分包写过去,所以对方要循环写完*/
  96. out.write(filelength);
  97. out.flush();
  98. Stringstrok1=readFromSocket(in);
  99. System.out.println("servicereceivefilelength:"+strok1);
  100. //out.write(fileformat);
  101. //out.flush();
  102. //Stringstrok2=readFromSocket(in);
  103. //System.out.println("servicereceivefileformat:"+
  104. //strok2);
  105. System.out.println("writedatatoandroid");
  106. out.write(filebytes);
  107. out.flush();
  108. System.out.println("*********");
  109. /*服务器反馈:接收成功*/
  110. Stringstrread=readFromSocket(in);
  111. System.out.println("senddatasuccess:"+strread);
  112. System.out
  113. .println("=============================================");
  114. }elseif(strWord.equalsIgnoreCase("EXIT")){
  115. out.write("EXIT".getBytes());
  116. out.flush();
  117. System.out.println("EXITfinishsendingthedata");
  118. StringstrFormsocket=readFromSocket(in);
  119. System.out.println("thedatasentbyserveris:/r/n"
  120. +strFormsocket);
  121. flag=false;
  122. System.out
  123. .println("=============================================");
  124. }
  125. }
  126. }catch(UnknownHostExceptione1){
  127. System.out.println("TCP331133"+"ERROR:"+e1.toString());
  128. }catch(Exceptione2){
  129. System.out.println("TCP441144"+"ERROR:"+e2.toString());
  130. }finally{
  131. try{
  132. if(socket!=null){
  133. socket.close();
  134. System.out.println("socket.close()");
  135. }
  136. }catch(IOExceptione){
  137. System.out.println("TCP5555"+"ERROR:"+e.toString());
  138. }
  139. }
  140. }
  141. /*从InputStream流中读数据*/
  142. publicstaticStringreadFromSocket(InputStreamin){
  143. intMAX_BUFFER_BYTES=4000;
  144. Stringmsg="";
  145. byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];
  146. try{
  147. intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);
  148. msg=newString(tempbuffer,0,numReadedBytes,"utf-8");
  149. tempbuffer=null;
  150. }catch(Exceptione){
  151. e.printStackTrace();
  152. }
  153. //Log.v(Service139.TAG,"msg="+msg);
  154. returnmsg;
  155. }
  156. }

android服务器端:

PC客户端与Android服务端的Socket同步通信(USB)

主类androidService.java

  1. packagecom.otheri.service;
  2. importjava.io.File;
  3. importjava.io.IOException;
  4. importjava.net.ServerSocket;
  5. importjava.net.Socket;
  6. importandroid.app.Service;
  7. importandroid.content.BroadcastReceiver;
  8. importandroid.content.Context;
  9. importandroid.content.Intent;
  10. importandroid.content.IntentFilter;
  11. importandroid.os.IBinder;
  12. importandroid.util.Log;
  13. /**
  14. *设置:android手机
  15. *
  16. *
  17. **/
  18. publicclassandroidServiceextendsService{
  19. publicstaticfinalStringTAG="TAG";
  20. publicstaticBooleanmainThreadFlag=true;
  21. publicstaticBooleanioThreadFlag=true;
  22. ServerSocketserverSocket=null;
  23. finalintSERVER_PORT=10086;
  24. FiletestFile;
  25. privatesysBroadcastReceiversysBR;
  26. @Override
  27. publicvoidonCreate(){
  28. super.onCreate();
  29. Log.v(TAG,Thread.currentThread().getName()+"---->"+"onCreate");
  30. /*创建内部类sysBroadcastReceiver并注册registerReceiver*/
  31. sysRegisterReceiver();
  32. newThread(){
  33. publicvoidrun(){
  34. doListen();
  35. };
  36. }.start();
  37. }
  38. privatevoiddoListen(){
  39. Log.d(TAG,Thread.currentThread().getName()+"---->"
  40. +"doListen()START");
  41. serverSocket=null;
  42. try{
  43. Log.d(TAG,Thread.currentThread().getName()+"---->"
  44. +"doListen()newserverSocket");
  45. serverSocket=newServerSocket(SERVER_PORT);
  46. booleanmainThreadFlag=true;
  47. while(mainThreadFlag){
  48. Log.d(TAG,Thread.currentThread().getName()+"---->"
  49. +"doListen()listen");
  50. Socketclient=serverSocket.accept();
  51. newThread(newThreadReadWriterIOSocket(this,client)).start();
  52. }
  53. }catch(IOExceptione1){
  54. Log.v(androidService.TAG,Thread.currentThread().getName()
  55. +"---->"+"newserverSocketerror");
  56. e1.printStackTrace();
  57. }
  58. }
  59. /*创建内部类sysBroadcastReceiver并注册registerReceiver*/
  60. privatevoidsysRegisterReceiver(){
  61. Log.v(TAG,Thread.currentThread().getName()+"---->"
  62. +"sysRegisterReceiver");
  63. sysBR=newsysBroadcastReceiver();
  64. /*注册BroadcastReceiver*/
  65. IntentFilterfilter1=newIntentFilter();
  66. /*新的应用程序被安装到了设备上的广播*/
  67. filter1.addAction("android.intent.action.PACKAGE_ADDED");
  68. filter1.addDataScheme("package");
  69. filter1.addAction("android.intent.action.PACKAGE_REMOVED");
  70. filter1.addDataScheme("package");
  71. registerReceiver(sysBR,filter1);
  72. }
  73. /*内部类:BroadcastReceiver用于接收系统事件*/
  74. privateclasssysBroadcastReceiverextendsBroadcastReceiver{
  75. @Override
  76. publicvoidonReceive(Contextcontext,Intentintent){
  77. Stringaction=intent.getAction();
  78. if(action.equalsIgnoreCase("android.intent.action.PACKAGE_ADDED")){
  79. //ReadInstalledAPP();
  80. }elseif(action
  81. .equalsIgnoreCase("android.intent.action.PACKAGE_REMOVED")){
  82. //ReadInstalledAPP();
  83. }
  84. Log.v(TAG,Thread.currentThread().getName()+"---->"
  85. +"sysBroadcastReceiveronReceive");
  86. }
  87. }
  88. @Override
  89. publicvoidonDestroy(){
  90. super.onDestroy();
  91. //关闭线程
  92. mainThreadFlag=false;
  93. ioThreadFlag=false;
  94. //关闭服务器
  95. try{
  96. Log.v(TAG,Thread.currentThread().getName()+"---->"
  97. +"serverSocket.close()");
  98. serverSocket.close();
  99. }catch(IOExceptione){
  100. e.printStackTrace();
  101. }
  102. Log.v(TAG,Thread.currentThread().getName()+"---->"
  103. +"****************onDestroy****************");
  104. }
  105. @Override
  106. publicvoidonStart(Intentintent,intstartId){
  107. Log.d(TAG,Thread.currentThread().getName()+"---->"+"onStart()");
  108. super.onStart(intent,startId);
  109. }
  110. @Override
  111. publicIBinderonBind(Intentarg0){
  112. Log.d(TAG,"onBind");
  113. returnnull;
  114. }
  115. }

用于接收PC发来的Broastcast并启动主类service的ServiceBroadcastReceiver.java

  1. packagecom.otheri.service;
  2. importandroid.content.BroadcastReceiver;
  3. importandroid.content.Context;
  4. importandroid.content.Intent;
  5. importandroid.util.Log;
  6. publicclassServiceBroadcastReceiverextendsBroadcastReceiver{
  7. privatestaticStringSTART_ACTION="NotifyServiceStart";
  8. privatestaticStringSTOP_ACTION="NotifyServiceStop";
  9. @Override
  10. publicvoidonReceive(Contextcontext,Intentintent){
  11. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  12. +"ServiceBroadcastReceiveronReceive");
  13. Stringaction=intent.getAction();
  14. if(START_ACTION.equalsIgnoreCase(action)){
  15. context.startService(newIntent(context,androidService.class));
  16. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  17. +"ServiceBroadcastReceiveronReceivestartend");
  18. }elseif(STOP_ACTION.equalsIgnoreCase(action)){
  19. context.stopService(newIntent(context,androidService.class));
  20. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  21. +"ServiceBroadcastReceiveronReceivestopend");
  22. }
  23. }
  24. }

用于新socket连接的读写线程类ThreadReadWriterIOSocket.java

  1. packagecom.otheri.service;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.BufferedOutputStream;
  4. importjava.io.ByteArrayOutputStream;
  5. importjava.io.File;
  6. importjava.io.IOException;
  7. importjava.io.InputStream;
  8. importjava.io.OutputStream;
  9. importjava.net.Socket;
  10. importandroid.content.Context;
  11. importandroid.util.Log;
  12. importcom.otheri.util.FileHelper;
  13. importcom.otheri.util.MyUtil;
  14. /**
  15. *功能:用于socket的交互
  16. *
  17. *@authorwufenglong
  18. *
  19. */
  20. publicclassThreadReadWriterIOSocketimplementsRunnable{
  21. privateSocketclient;
  22. privateContextcontext;
  23. ThreadReadWriterIOSocket(Contextcontext,Socketclient){
  24. this.client=client;
  25. this.context=context;
  26. }
  27. @Override
  28. publicvoidrun(){
  29. Log.d(androidService.TAG,Thread.currentThread().getName()+"---->"
  30. +"aclienthasconnectedtoserver!");
  31. BufferedOutputStreamout;
  32. BufferedInputStreamin;
  33. try{
  34. /*PC端发来的数据msg*/
  35. StringcurrCMD="";
  36. out=newBufferedOutputStream(client.getOutputStream());
  37. in=newBufferedInputStream(client.getInputStream());
  38. //testSocket();//测试socket方法
  39. androidService.ioThreadFlag=true;
  40. while(androidService.ioThreadFlag){
  41. try{
  42. if(!client.isConnected()){
  43. break;
  44. }
  45. /*接收PC发来的数据*/
  46. Log.v(androidService.TAG,Thread.currentThread().getName()
  47. +"---->"+"willread......");
  48. /*读操作命令*/
  49. currCMD=readCMDFromSocket(in);
  50. Log.v(androidService.TAG,Thread.currentThread().getName()
  51. +"---->"+"**currCMD===="+currCMD);
  52. /*根据命令分别处理数据*/
  53. if(currCMD.equals("1")){
  54. out.write("OK".getBytes());
  55. out.flush();
  56. }elseif(currCMD.equals("2")){
  57. out.write("OK".getBytes());
  58. out.flush();
  59. }elseif(currCMD.equals("3")){
  60. out.write("OK".getBytes());
  61. out.flush();
  62. }elseif(currCMD.equals("4")){
  63. /*准备接收文件数据*/
  64. try{
  65. out.write("servicereceiveOK".getBytes());
  66. out.flush();
  67. }catch(IOExceptione){
  68. e.printStackTrace();
  69. }
  70. /*接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据*/
  71. byte[]filelength=newbyte[4];
  72. byte[]fileformat=newbyte[4];
  73. byte[]filebytes=null;
  74. /*从socket流中读取完整文件数据*/
  75. filebytes=receiveFileFromSocket(in,out,filelength,
  76. fileformat);
  77. //Log.v(Service139.TAG,"receivedata="+new
  78. //String(filebytes));
  79. try{
  80. /*生成文件*/
  81. Filefile=FileHelper.newFile("R0013340.JPG");
  82. FileHelper.writeFile(file,filebytes,0,
  83. filebytes.length);
  84. }catch(IOExceptione){
  85. e.printStackTrace();
  86. }
  87. }elseif(currCMD.equals("exit")){
  88. }
  89. }catch(Exceptione){
  90. //try{
  91. //out.write("error".getBytes("utf-8"));
  92. //out.flush();
  93. //}catch(IOExceptione1){
  94. //e1.printStackTrace();
  95. //}
  96. Log.e(androidService.TAG,Thread.currentThread().getName()
  97. +"---->"+"readwriteerror111111");
  98. }
  99. }
  100. out.close();
  101. in.close();
  102. }catch(Exceptione){
  103. Log.e(androidService.TAG,Thread.currentThread().getName()
  104. +"---->"+"readwriteerror222222");
  105. e.printStackTrace();
  106. }finally{
  107. try{
  108. if(client!=null){
  109. Log.v(androidService.TAG,Thread.currentThread().getName()
  110. +"---->"+"client.close()");
  111. client.close();
  112. }
  113. }catch(IOExceptione){
  114. Log.e(androidService.TAG,Thread.currentThread().getName()
  115. +"---->"+"readwriteerror333333");
  116. e.printStackTrace();
  117. }
  118. }
  119. }
  120. /**
  121. *功能:从socket流中读取完整文件数据
  122. *
  123. *InputStreamin:socket输入流
  124. *
  125. *byte[]filelength:流的前4个字节存储要转送的文件的字节数
  126. *
  127. *byte[]fileformat:流的前5-8字节存储要转送的文件的格式(如.apk)
  128. *
  129. **/
  130. publicstaticbyte[]receiveFileFromSocket(InputStreamin,
  131. OutputStreamout,byte[]filelength,byte[]fileformat){
  132. byte[]filebytes=null;//文件数据
  133. try{
  134. in.read(filelength);//读文件长度
  135. intfilelen=MyUtil.bytesToInt(filelength);//文件长度从4字节byte[]转成Int
  136. Stringstrtmp="readfilelengthok:"+filelen;
  137. out.write(strtmp.getBytes("utf-8"));
  138. out.flush();
  139. filebytes=newbyte[filelen];
  140. intpos=0;
  141. intrcvLen=0;
  142. while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){
  143. pos+=rcvLen;
  144. }
  145. Log.v(androidService.TAG,Thread.currentThread().getName()
  146. +"---->"+"readfileOK:filesize="+filebytes.length);
  147. out.write("readfileok".getBytes("utf-8"));
  148. out.flush();
  149. }catch(Exceptione){
  150. Log.v(androidService.TAG,Thread.currentThread().getName()
  151. +"---->"+"receiveFileFromSocketerror");
  152. e.printStackTrace();
  153. }
  154. returnfilebytes;
  155. }
  156. /*读取命令*/
  157. publicstaticStringreadCMDFromSocket(InputStreamin){
  158. intMAX_BUFFER_BYTES=2048;
  159. Stringmsg="";
  160. byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];
  161. try{
  162. intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);
  163. msg=newString(tempbuffer,0,numReadedBytes,"utf-8");
  164. tempbuffer=null;
  165. }catch(Exceptione){
  166. Log.v(androidService.TAG,Thread.currentThread().getName()
  167. +"---->"+"readFromSocketerror");
  168. e.printStackTrace();
  169. }
  170. //Log.v(Service139.TAG,"msg="+msg);
  171. returnmsg;
  172. }
  173. }

后面是两个辅助类:

  1. packagecom.otheri.util;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.File;
  4. importjava.io.FileInputStream;
  5. importjava.io.FileOutputStream;
  6. importjava.io.IOException;
  7. importcom.otheri.service.androidService;
  8. importandroid.util.Log;
  9. publicclassFileHelper{
  10. //privatestaticStringFILEPATH="/data/local/tmp";
  11. privatestaticStringFILEPATH="/sdcard";
  12. //privatestaticStringFILEPATH="/tmp";
  13. publicstaticFilenewFile(StringfileName){
  14. Filefile=null;
  15. try{
  16. file=newFile(FILEPATH,fileName);
  17. file.delete();
  18. file.createNewFile();
  19. }catch(IOExceptione){
  20. //TODOAuto-generatedcatchblock
  21. e.printStackTrace();
  22. }
  23. returnfile;
  24. }
  25. publicstaticvoidwriteFile(Filefile,byte[]data,intoffset,intcount)
  26. throwsIOException{
  27. FileOutputStreamfos=newFileOutputStream(file,true);
  28. fos.write(data,offset,count);
  29. fos.flush();
  30. fos.close();
  31. }
  32. publicstaticbyte[]readFile(StringfileName)throwsIOException{
  33. Filefile=newFile(FILEPATH,fileName);
  34. file.createNewFile();
  35. FileInputStreamfis=newFileInputStream(file);
  36. BufferedInputStreambis=newBufferedInputStream(fis);
  37. intleng=bis.available();
  38. Log.v(androidService.TAG,"filesize="+leng);
  39. byte[]b=newbyte[leng];
  40. bis.read(b,0,leng);
  41. //Inputin=newInput(fis);
  42. //byte[]ret=in.readAll();
  43. //in.close();
  44. bis.close();
  45. returnb;
  46. }
  47. }
  1. packagecom.otheri.util;
  2. importjava.io.InputStream;
  3. importandroid.util.Log;
  4. importcom.otheri.service.androidService;
  5. publicclassMyUtil{
  6. /*byte[]转Int*/
  7. publicstaticintbytesToInt(byte[]bytes){
  8. intaddr=bytes[0]&0xFF;
  9. addr|=((bytes[1]<<8)&0xFF00);
  10. addr|=((bytes[2]<<16)&0xFF0000);
  11. addr|=((bytes[3]<<24)&0xFF000000);
  12. returnaddr;
  13. }
  14. /*Int转byte[]*/
  15. publicstaticbyte[]intToByte(inti){
  16. byte[]abyte0=newbyte[4];
  17. abyte0[0]=(byte)(0xff&i);
  18. abyte0[1]=(byte)((0xff00&i)>>8);
  19. abyte0[2]=(byte)((0xff0000&i)>>16);
  20. abyte0[3]=(byte)((0xff000000&i)>>24);
  21. returnabyte0;
  22. }
  23. }

你可能感兴趣的:(android)