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( "adb forward tcp:12580 tcp:10086" );  
  2.             Thread.sleep(3000 );  
复制代码
  1. Runtime.getRuntime().exec("adb forward tcp:12580 tcp: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. "adb shell am broadcast -a NotifyServiceStart" );  
复制代码
  1. Runtime.getRuntime().exec(
  2. "adb shell am broadcast -a NotifyServiceStart");
复制代码
android端的代码:ServiceBroadcastReceiver.java
  1. package  com.otheri.service;  
  2.   
  3. import  android.content.BroadcastReceiver;  
  4. import  android.content.Context;  
  5. import  android.content.Intent;  
  6. import  android.util.Log;  
  7.   
  8. public   class  ServiceBroadcastReceiver  extends  BroadcastReceiver {  
  9.     private   static  String START_ACTION =  "NotifyServiceStart" ;  
  10.     private   static  String STOP_ACTION =  "NotifyServiceStop" ;  
  11.   
  12.     @Override   
  13.     public   void  onReceive(Context context, Intent intent) {  
  14.         Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"   
  15.                 + "ServiceBroadcastReceiver onReceive" );  
  16.   
  17.         String action = intent.getAction();  
  18.         if  (START_ACTION.equalsIgnoreCase(action)) {  
  19.             context.startService(new  Intent(context, androidService. class ));  
  20.   
  21.             Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"   
  22.                     + "ServiceBroadcastReceiver onReceive start end" );  
  23.         } else   if  (STOP_ACTION.equalsIgnoreCase(action)) {  
  24.             context.stopService(new  Intent(context, androidService. class ));  
  25.             Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"   
  26.                     + "ServiceBroadcastReceiver onReceive stop end" );  
  27.         }  
  28.     }  
  29.   
  30. }  
复制代码
  1. package com.otheri.service;  
  2. import android.content.BroadcastReceiver;  
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.util.Log;  
  6. public class ServiceBroadcastReceiver extends BroadcastReceiver {  
  7.     private static String START_ACTION = "NotifyServiceStart";  
  8.     private static String STOP_ACTION = "NotifyServiceStop";  
  9.     @Override  
  10.     public void onReceive(Context context, Intent intent) {  
  11.         Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
  12.                 + "ServiceBroadcastReceiver onReceive");  
  13.         String action = intent.getAction();  
  14.         if (START_ACTION.equalsIgnoreCase(action)) {  
  15.             context.startService(new Intent(context, androidService.class));  
  16.             Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
  17.                     + "ServiceBroadcastReceiver onReceive start end");  
  18.         } else if (STOP_ACTION.equalsIgnoreCase(action)) {  
  19.             context.stopService(new Intent(context, androidService.class));  
  20.             Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
  21.                     + "ServiceBroadcastReceiver onReceive stop end");  
  22.         }  
  23.     }  
  24. }  
复制代码

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

    android的代码:

  1. public   void  run() {  
  2.         Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"   
  3.                 + "a client has connected to server!" );  
  4.         BufferedOutputStream out;  
  5.         BufferedInputStream in;  
  6.         try  {  
  7.             /* PC端发来的数据msg */   
  8.             String currCMD = "" ;  
  9.             out = new  BufferedOutputStream(client.getOutputStream());  
  10.             in = new  BufferedInputStream(client.getInputStream());  
  11.             // testSocket();// 测试socket方法   
  12.             androidService.ioThreadFlag = true ;  
  13.             while  (androidService.ioThreadFlag) {  
  14.                 try  {  
  15.                     if  (!client.isConnected()) {  
  16.                         break ;  
  17.                     }  
  18.   
  19.                     /* 接收PC发来的数据 */   
  20.                     Log.v(androidService.TAG, Thread.currentThread().getName()  
  21.                             + "---->"  +  "will read......" );  
  22.                     /* 读操作命令 */   
  23.                     currCMD = readCMDFromSocket(in);  
  24.                     Log.v(androidService.TAG, Thread.currentThread().getName()  
  25.                             + "---->"  +  "**currCMD ==== "  + currCMD);  
  26.   
  27.                     /* 根据命令分别处理数据 */   
  28.                     if  (currCMD.equals( "1" )) {  
  29.                         out.write("OK" .getBytes());  
  30.                         out.flush();  
  31.                     } else   if  (currCMD.equals( "2" )) {  
  32.                         out.write("OK" .getBytes());  
  33.                         out.flush();  
  34.                     } else   if  (currCMD.equals( "3" )) {  
  35.                         out.write("OK" .getBytes());  
  36.                         out.flush();  
  37.                     } else   if  (currCMD.equals( "4" )) {  
  38.                         /* 准备接收文件数据 */   
  39.                         try  {  
  40.                             out.write("service receive OK" .getBytes());  
  41.                             out.flush();  
  42.                         } catch  (IOException e) {  
  43.                             e.printStackTrace();  
  44.                         }  
  45.   
  46.                         /* 接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据 */   
  47.                         byte [] filelength =  new   byte [ 4 ];  
  48.                         byte [] fileformat =  new   byte [ 4 ];  
  49.                         byte [] filebytes =  null ;  
  50.   
  51.                         /* 从socket流中读取完整文件数据 */   
  52.                         filebytes = receiveFileFromSocket(in, out, filelength,  
  53.                                 fileformat);  
  54.   
  55.                         // Log.v(Service139.TAG, "receive data =" + new   
  56.                         // String(filebytes));   
  57.                         try  {  
  58.                             /* 生成文件 */   
  59.                             File file = FileHelper.newFile("R0013340.JPG" );  
  60.                             FileHelper.writeFile(file, filebytes, 0 ,  
  61.                                     filebytes.length);  
  62.                         } catch  (IOException e) {  
  63.                             e.printStackTrace();  
  64.                         }  
  65.                     } else   if  (currCMD.equals( "exit" )) {  
  66.   
  67.                     }  
  68.                 } catch  (Exception e) {  
  69.                     // try {   
  70.                     // out.write("error".getBytes("utf-8"));   
  71.                     // out.flush();   
  72.                     // } catch (IOException e1) {   
  73.                     // e1.printStackTrace();   
  74.                     // }   
  75.                     Log.e(androidService.TAG, Thread.currentThread().getName()  
  76.                             + "---->"  +  "read write error111111" );  
  77.                 }  
  78.             }  
  79.             out.close();  
  80.             in.close();  
  81.         } catch  (Exception e) {  
  82.             Log.e(androidService.TAG, Thread.currentThread().getName()  
  83.                     + "---->"  +  "read write error222222" );  
  84.             e.printStackTrace();  
  85.         } finally  {  
  86.             try  {  
  87.                 if  (client !=  null ) {  
  88.                     Log.v(androidService.TAG, Thread.currentThread().getName()  
  89.                             + "---->"  +  "client.close()" );  
  90.                     client.close();  
  91.                 }  
  92.             } catch  (IOException e) {  
  93.                 Log.e(androidService.TAG, Thread.currentThread().getName()  
  94.                         + "---->"  +  "read write error333333" );  
  95.                 e.printStackTrace();  
  96.             }  
  97.         }  
复制代码
  1. public void run() {
  2.                 Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"
  3.                                 + "a client has connected to server!");
  4.                 BufferedOutputStream out;
  5.                 BufferedInputStream in;
  6.                 try {
  7.                         /* PC端发来的数据msg */
  8.                         String currCMD = "";
  9.                         out = new BufferedOutputStream(client.getOutputStream());
  10.                         in = new BufferedInputStream(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.                                                         + "---->" + "will read......");
  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.                                         } else if (currCMD.equals("2")) {
  30.                                                 out.write("OK".getBytes());
  31.                                                 out.flush();
  32.                                         } else if (currCMD.equals("3")) {
  33.                                                 out.write("OK".getBytes());
  34.                                                 out.flush();
  35.                                         } else if (currCMD.equals("4")) {
  36.                                                 /* 准备接收文件数据 */
  37.                                                 try {
  38.                                                         out.write("service receive OK".getBytes());
  39.                                                         out.flush();
  40.                                                 } catch (IOException e) {
  41.                                                         e.printStackTrace();
  42.                                                 }
  43.                                                 /* 接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据 */
  44.                                                 byte[] filelength = new byte[4];
  45.                                                 byte[] fileformat = new byte[4];
  46.                                                 byte[] filebytes = null;
  47.                                                 /* 从socket流中读取完整文件数据 */
  48.                                                 filebytes = receiveFileFromSocket(in, out, filelength,
  49.                                                                 fileformat);
  50.                                                 // Log.v(Service139.TAG, "receive data =" + new
  51.                                                 // String(filebytes));
  52.                                                 try {
  53.                                                         /* 生成文件 */
  54.                                                         File file = FileHelper.newFile("R0013340.JPG");
  55.                                                         FileHelper.writeFile(file, filebytes, 0,
  56.                                                                         filebytes.length);
  57.                                                 } catch (IOException e) {
  58.                                                         e.printStackTrace();
  59.                                                 }
  60.                                         } else if (currCMD.equals("exit")) {
  61.                                         }
  62.                                 } catch (Exception e) {
  63.                                         // try {
  64.                                         // out.write("error".getBytes("utf-8"));
  65.                                         // out.flush();
  66.                                         // } catch (IOException e1) {
  67.                                         // e1.printStackTrace();
  68.                                         // }
  69.                                         Log.e(androidService.TAG, Thread.currentThread().getName()
  70.                                                         + "---->" + "read write error111111");
  71.                                 }
  72.                         }
  73.                         out.close();
  74.                         in.close();
  75.                 } catch (Exception e) {
  76.                         Log.e(androidService.TAG, Thread.currentThread().getName()
  77.                                         + "---->" + "read write error222222");
  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 (IOException e) {
  87.                                 Log.e(androidService.TAG, Thread.currentThread().getName()
  88.                                                 + "---->" + "read write error333333");
  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.      * InputStream in:socket输入流  
  5.      *   
  6.      * byte[] filelength: 流的前4个字节存储要转送的文件的字节数  
  7.      *   
  8.      * byte[] fileformat:流的前5-8字节存储要转送的文件的格式(如.apk)  
  9.      *   
  10.      * */   
  11.     public   static   byte [] receiveFileFromSocket(InputStream in,  
  12.             OutputStream out, byte [] filelength,  byte [] fileformat) {  
  13.         byte [] filebytes =  null ; // 文件数据   
  14.         try  {  
  15.             int  filelen = MyUtil.bytesToInt(filelength); // 文件长度从4字节byte[]转成Int   
  16.             String strtmp = "read file length ok:"  + filelen;  
  17.             out.write(strtmp.getBytes("utf-8" ));  
  18.             out.flush();  
  19.   
  20.             filebytes = new   byte [filelen];  
  21.             int  pos =  0 ;  
  22.             int  rcvLen =  0 ;  
  23.             while  ((rcvLen = in.read(filebytes, pos, filelen - pos)) >  0 ) {  
  24.                 pos += rcvLen;  
  25.             }  
  26.             Log.v(androidService.TAG, Thread.currentThread().getName()  
  27.                     + "---->"  +  "read file OK:file size="  + filebytes.length);  
  28.             out.write("read file ok" .getBytes( "utf-8" ));  
  29.             out.flush();  
  30.         } catch  (Exception e) {  
  31.             Log.v(androidService.TAG, Thread.currentThread().getName()  
  32.                     + "---->"  +  "receiveFileFromSocket error" );  
  33.             e.printStackTrace();  
  34.         }  
  35.         return  filebytes;  
  36.     }  
复制代码
  1. /** 
  2.      * 功能:从socket流中读取完整文件数据 
  3.      *  
  4.      * InputStream in:socket输入流 
  5.      *  
  6.      * byte[] filelength: 流的前4个字节存储要转送的文件的字节数 
  7.      *  
  8.      * byte[] fileformat:流的前5-8字节存储要转送的文件的格式(如.apk) 
  9.      *  
  10.      * */  
  11.     public static byte[] receiveFileFromSocket(InputStream in,  
  12.             OutputStream out, byte[] filelength, byte[] fileformat) {  
  13.         byte[] filebytes = null;// 文件数据  
  14.         try {  
  15.             int filelen = MyUtil.bytesToInt(filelength);// 文件长度从4字节byte[]转成Int  
  16.             String strtmp = "read file length ok:" + filelen;  
  17.             out.write(strtmp.getBytes("utf-8"));  
  18.             out.flush();  
  19.             filebytes = new byte[filelen];  
  20.             int pos = 0;  
  21.             int rcvLen = 0;  
  22.             while ((rcvLen = in.read(filebytes, pos, filelen - pos)) > 0) {  
  23.                 pos += rcvLen;  
  24.             }  
  25.             Log.v(androidService.TAG, Thread.currentThread().getName()  
  26.                     + "---->" + "read file OK:file size=" + filebytes.length);  
  27.             out.write("read file ok".getBytes("utf-8"));  
  28.             out.flush();  
  29.         } catch (Exception e) {  
  30.             Log.v(androidService.TAG, Thread.currentThread().getName()  
  31.                     + "---->" + "receiveFileFromSocket error");  
  32.             e.printStackTrace();  
  33.         }  
  34.         return filebytes;  
  35.     }  
复制代码

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

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

源码:

客户端(pc端):

150053tlx5z5jlq8o8le5t.jpg





testPcClient.java

  1. import  java.io.BufferedInputStream;  
  2. import  java.io.BufferedOutputStream;  
  3. import  java.io.BufferedReader;  
  4. import  java.io.ByteArrayOutputStream;  
  5. import  java.io.IOException;  
  6. import  java.io.InputStream;  
  7. import  java.io.InputStreamReader;  
  8. import  java.net.InetAddress;  
  9. import  java.net.Socket;  
  10. import  java.net.UnknownHostException;  
  11.   
  12. public   class  testPcClient {  
  13.   
  14.     /**  
  15.      * @param args  
  16.      * @throws InterruptedException  
  17.      */   
  18.     public   static   void  main(String[] args)  throws  InterruptedException {  
  19.         try  {  
  20.             Runtime.getRuntime().exec(  
  21.                     "adb shell am broadcast -a NotifyServiceStop" );  
  22.             Thread.sleep(3000 );  
  23.             Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086" );  
  24.             Thread.sleep(3000 );  
  25.             Runtime.getRuntime().exec(  
  26.                     "adb shell am broadcast -a NotifyServiceStart" );  
  27.             Thread.sleep(3000 );  
  28.         } catch  (IOException e3) {  
  29.             e3.printStackTrace();  
  30.         }  
  31.   
  32.         Socket socket = null ;  
  33.         try  {  
  34.             InetAddress serverAddr = null ;  
  35.             serverAddr = InetAddress.getByName("127.0.0.1" );  
  36.             System.out.println("TCP 1111"  +  "C: Connecting..." );  
  37.             socket = new  Socket(serverAddr,  12580 );  
  38.             String str = "hi,wufenglong" ;  
  39.             System.out.println("TCP 221122"  +  "C:RECEIVE" );  
  40.             BufferedOutputStream out = new  BufferedOutputStream(socket  
  41.                     .getOutputStream());  
  42.             BufferedInputStream in = new  BufferedInputStream(socket  
  43.                     .getInputStream());  
  44.             BufferedReader br = new  BufferedReader( new  InputStreamReader(  
  45.                     System.in));  
  46.             boolean  flag =  true ;  
  47.             while  (flag) {  
  48.                 System.out.print("请输入1~6的数字,退出输入exit:" );  
  49.                 String strWord = br.readLine();// 从控制台输入1~6   
  50.                 if  (strWord.equals( "1" )) {  
  51.                     out.write("1" .getBytes());  
  52.                     out.flush();  
  53.                     System.out.println("1 finish sending the data" );  
  54.                     String strFormsocket = readFromSocket(in);  
  55.                     System.out.println("the data sent by server is:"   
  56.                             + strFormsocket);  
  57.                     System.out  
  58.                             .println("=============================================" );  
  59.                 } else   if  (strWord.equals( "2" )) {  
  60.                     out.write("2" .getBytes());  
  61.                     out.flush();  
  62.                     System.out.println("2 finish sending the data" );  
  63.                     String strFormsocket = readFromSocket(in);  
  64.                     System.out.println("the data sent by server is:"   
  65.                             + strFormsocket);  
  66.                     System.out  
  67.                             .println("=============================================" );  
  68.                 } else   if  (strWord.equals( "3" )) {  
  69.                     out.write("3" .getBytes());  
  70.                     out.flush();  
  71.                     System.out.println("3 finish sending the data" );  
  72.                     String strFormsocket = readFromSocket(in);  
  73.                     System.out.println("the data sent by server is:"   
  74.                             + strFormsocket);  
  75.                     System.out  
  76.                             .println("=============================================" );  
  77.                 } else   if  (strWord.equals( "4" )) {  
  78.                     /* 发送命令 */   
  79.                     out.write("4" .getBytes());  
  80.                     out.flush();  
  81.                     System.out.println("send file finish sending the CMD:" );  
  82.                     /* 服务器反馈:准备接收 */   
  83.                     String strFormsocket = readFromSocket(in);  
  84.                     System.out  
  85.                             .println("service ready receice data:UPDATE_CONTACTS:"   
  86.                                     + strFormsocket);  
  87.                     byte [] filebytes = FileHelper.readFile( "R0013340.JPG" );  
  88.                     System.out.println("file size="  + filebytes.length);  
  89.                     /* 将整数转成4字节byte数组 */   
  90.                     byte [] filelength =  new   byte [ 4 ];  
  91.                     filelength = tools.intToByte(filebytes.length);  
  92.                     /* 将.apk字符串转成4字节byte数组 */   
  93.                     byte [] fileformat =  null ;  
  94.                     fileformat = ".apk" .getBytes();  
  95.                     System.out  
  96.                             .println("fileformat length="  + fileformat.length);  
  97.                     /* 字节流中前4字节为文件长度,4字节文件格式,以后是文件流 */   
  98.                     /* 注意如果write里的byte[]超过socket的缓存,系统自动分包写过去,所以对方要循环写完 */   
  99.                     out.write(filelength);  
  100.                     out.flush();  
  101.                     String strok1 = readFromSocket(in);  
  102.                     System.out.println("service receive filelength :"  + strok1);  
  103.                     // out.write(fileformat);   
  104.                     // out.flush();   
  105.                     // String strok2 = readFromSocket(in);   
  106.                     // System.out.println("service receive fileformat :" +   
  107.                     // strok2);   
  108.                     System.out.println("write data to android" );  
  109.                     out.write(filebytes);  
  110.                     out.flush();  
  111.                     System.out.println("*********" );  
  112.   
  113.                     /* 服务器反馈:接收成功 */   
  114.                     String strread = readFromSocket(in);  
  115.                     System.out.println(" send data success:"  + strread);  
  116.                     System.out  
  117.                             .println("=============================================" );  
  118.                 } else   if  (strWord.equalsIgnoreCase( "EXIT" )) {  
  119.                     out.write("EXIT" .getBytes());  
  120.                     out.flush();  
  121.                     System.out.println("EXIT finish sending the data" );  
  122.                     String strFormsocket = readFromSocket(in);  
  123.                     System.out.println("the data sent by server is:"   
  124.                             + strFormsocket);  
  125.                     flag = false ;  
  126.                     System.out  
  127.                             .println("=============================================" );  
  128.                 }  
  129.             }  
  130.   
  131.         } catch  (UnknownHostException e1) {  
  132.             System.out.println("TCP 331133"  +  "ERROR:"  + e1.toString());  
  133.         } catch  (Exception e2) {  
  134.             System.out.println("TCP 441144"  +  "ERROR:"  + e2.toString());  
  135.         } finally  {  
  136.             try  {  
  137.                 if  (socket !=  null ) {  
  138.                     socket.close();  
  139.                     System.out.println("socket.close()" );  
  140.                 }  
  141.             } catch  (IOException e) {  
  142.                 System.out.println("TCP 5555"  +  "ERROR:"  + e.toString());  
  143.             }  
  144.         }  
  145.     }  
  146.   
  147.     /* 从InputStream流中读数据 */   
  148.     public   static  String readFromSocket(InputStream in) {  
  149.         int  MAX_BUFFER_BYTES =  4000 ;  
  150.         String msg = "" ;  
  151.         byte [] tempbuffer =  new   byte [MAX_BUFFER_BYTES];  
  152.         try  {  
  153.             int  numReadedBytes = in.read(tempbuffer,  0 , tempbuffer.length);  
  154.             msg = new  String(tempbuffer,  0 , numReadedBytes,  "utf-8" );  
  155.   
  156.             tempbuffer = null ;  
  157.         } catch  (Exception e) {  
  158.             e.printStackTrace();  
  159.         }  
  160.         // Log.v(Service139.TAG, "msg=" + msg);   
  161.         return  msg;  
  162.     }  
  163. }  
复制代码
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.BufferedReader;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.net.InetAddress;
  9. import java.net.Socket;
  10. import java.net.UnknownHostException;
  11. public class testPcClient {
  12.         /**
  13.          * @param args
  14.          * @throws InterruptedException
  15.          */
  16.         public static void main(String[] args) throws InterruptedException {
  17.                 try {
  18.                         Runtime.getRuntime().exec(
  19.                                         "adb shell am broadcast -a NotifyServiceStop");
  20.                         Thread.sleep(3000);
  21.                         Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086");
  22.                         Thread.sleep(3000);
  23.                         Runtime.getRuntime().exec(
  24.                                         "adb shell am broadcast -a NotifyServiceStart");
  25.                         Thread.sleep(3000);
  26.                 } catch (IOException e3) {
  27.                         e3.printStackTrace();
  28.                 }
  29.                 Socket socket = null;
  30.                 try {
  31.                         InetAddress serverAddr = null;
  32.                         serverAddr = InetAddress.getByName("127.0.0.1");
  33.                         System.out.println("TCP 1111" + "C: Connecting...");
  34.                         socket = new Socket(serverAddr, 12580);
  35.                         String str = "hi,wufenglong";
  36.                         System.out.println("TCP 221122" + "C:RECEIVE");
  37.                         BufferedOutputStream out = new BufferedOutputStream(socket
  38.                                         .getOutputStream());
  39.                         BufferedInputStream in = new BufferedInputStream(socket
  40.                                         .getInputStream());
  41.                         BufferedReader br = new BufferedReader(new InputStreamReader(
  42.                                         System.in));
  43.                         boolean flag = true;
  44.                         while (flag) {
  45.                                 System.out.print("请输入1~6的数字,退出输入exit:");
  46.                                 String strWord = br.readLine();// 从控制台输入1~6
  47.                                 if (strWord.equals("1")) {
  48.                                         out.write("1".getBytes());
  49.                                         out.flush();
  50.                                         System.out.println("1 finish sending the data");
  51.                                         String strFormsocket = readFromSocket(in);
  52.                                         System.out.println("the data sent by server is:"
  53.                                                         + strFormsocket);
  54.                                         System.out
  55.                                                         .println("=============================================");
  56.                                 } else if (strWord.equals("2")) {
  57.                                         out.write("2".getBytes());
  58.                                         out.flush();
  59.                                         System.out.println("2 finish sending the data");
  60.                                         String strFormsocket = readFromSocket(in);
  61.                                         System.out.println("the data sent by server is:"
  62.                                                         + strFormsocket);
  63.                                         System.out
  64.                                                         .println("=============================================");
  65.                                 } else if (strWord.equals("3")) {
  66.                                         out.write("3".getBytes());
  67.                                         out.flush();
  68.                                         System.out.println("3 finish sending the data");
  69.                                         String strFormsocket = readFromSocket(in);
  70.                                         System.out.println("the data sent by server is:"
  71.                                                         + strFormsocket);
  72.                                         System.out
  73.                                                         .println("=============================================");
  74.                                 } else if (strWord.equals("4")) {
  75.                                         /* 发送命令 */
  76.                                         out.write("4".getBytes());
  77.                                         out.flush();
  78.                                         System.out.println("send file finish sending the CMD:");
  79.                                         /* 服务器反馈:准备接收 */
  80.                                         String strFormsocket = readFromSocket(in);
  81.                                         System.out
  82.                                                         .println("service ready receice data:UPDATE_CONTACTS:"
  83.                                                                         + strFormsocket);
  84.                                         byte[] filebytes = FileHelper.readFile("R0013340.JPG");
  85.                                         System.out.println("file size=" + filebytes.length);
  86.                                         /* 将整数转成4字节byte数组 */
  87.                                         byte[] filelength = new byte[4];
  88.                                         filelength = tools.intToByte(filebytes.length);
  89.                                         /* 将.apk字符串转成4字节byte数组 */
  90.                                         byte[] fileformat = null;
  91.                                         fileformat = ".apk".getBytes();
  92.                                         System.out
  93.                                                         .println("fileformat length=" + fileformat.length);
  94.                                         /* 字节流中前4字节为文件长度,4字节文件格式,以后是文件流 */
  95.                                         /* 注意如果write里的byte[]超过socket的缓存,系统自动分包写过去,所以对方要循环写完 */
  96.                                         out.write(filelength);
  97.                                         out.flush();
  98.                                         String strok1 = readFromSocket(in);
  99.                                         System.out.println("service receive filelength :" + strok1);
  100.                                         // out.write(fileformat);
  101.                                         // out.flush();
  102.                                         // String strok2 = readFromSocket(in);
  103.                                         // System.out.println("service receive fileformat :" +
  104.                                         // strok2);
  105.                                         System.out.println("write data to android");
  106.                                         out.write(filebytes);
  107.                                         out.flush();
  108.                                         System.out.println("*********");
  109.                                         /* 服务器反馈:接收成功 */
  110.                                         String strread = readFromSocket(in);
  111.                                         System.out.println(" send data success:" + strread);
  112.                                         System.out
  113.                                                         .println("=============================================");
  114.                                 } else if (strWord.equalsIgnoreCase("EXIT")) {
  115.                                         out.write("EXIT".getBytes());
  116.                                         out.flush();
  117.                                         System.out.println("EXIT finish sending the data");
  118.                                         String strFormsocket = readFromSocket(in);
  119.                                         System.out.println("the data sent by server is:"
  120.                                                         + strFormsocket);
  121.                                         flag = false;
  122.                                         System.out
  123.                                                         .println("=============================================");
  124.                                 }
  125.                         }
  126.                 } catch (UnknownHostException e1) {
  127.                         System.out.println("TCP 331133" + "ERROR:" + e1.toString());
  128.                 } catch (Exception e2) {
  129.                         System.out.println("TCP 441144" + "ERROR:" + e2.toString());
  130.                 } finally {
  131.                         try {
  132.                                 if (socket != null) {
  133.                                         socket.close();
  134.                                         System.out.println("socket.close()");
  135.                                 }
  136.                         } catch (IOException e) {
  137.                                 System.out.println("TCP 5555" + "ERROR:" + e.toString());
  138.                         }
  139.                 }
  140.         }
  141.         /* 从InputStream流中读数据 */
  142.         public static String readFromSocket(InputStream in) {
  143.                 int MAX_BUFFER_BYTES = 4000;
  144.                 String msg = "";
  145.                 byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];
  146.                 try {
  147.                         int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
  148.                         msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
  149.                         tempbuffer = null;
  150.                 } catch (Exception e) {
  151.                         e.printStackTrace();
  152.                 }
  153.                 // Log.v(Service139.TAG, "msg=" + msg);
  154.                 return msg;
  155.         }
  156. }
复制代码

android服务器端:

150054d2e6dqce7cm7m7mb.jpg





主类androidService.java

  1. package  com.otheri.service; 
  2. import  java.io.File;  
复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值