PC客户端与Android服务端的Socket同步通信USB_第1页
PC客户端与Android服务端的Socket同步通信USB_第2页
PC客户端与Android服务端的Socket同步通信USB_第3页
PC客户端与Android服务端的Socket同步通信USB_第4页
PC客户端与Android服务端的Socket同步通信USB_第5页
免费预览已结束,剩余21页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、http:/ 客户端与 Android 服务端的 Socket 同步通信(USB)分类:android2010-07-3117:238027 人阅读评论(52)收藏举报需求:1 .一个 android 端的 service 后台运行的程序,作为 socket 的服务器端;用于接收 Pcclient 端发来的命令,来处理数据后,把 Z果发给 PCclient2.PC 端程序,作为 socket 的客户端,用于给 android 手机端发操作命令难点分析:1 .手机一定要有 adb 模式,即插上 USB 线时马上提示白对话框选 adb。好多对手机的操作都可以用 adb 直接作。不过,我发现 LGG

2、W880 就没有,要去下载个2 .android 默认手机端的 IP 为“”3 .要想联通 PC 与 android 手机的 sokcet,一定要用 adbforward 来作下端口转发才能连上 socket.viewplaincopytoclipboardprint?1.Runtime.getRuntime().exec(adbforwardtcp:12580tcp:10086);2.Thread.sleep(3000);Runtime.getRuntime().exec(adbforwardtcp:12580tcThread.sleep(3000);一4.android

3、端的 service 程序 Install 到手机上容易,但是还要有方法来从 PC 的 client 端来启动手机上的 service,这个办法可以通过PC 端 adb 命令来发一个 Broastcast,手机端再写个接收 BroastcastReceive 来接收这个 Broastcast,在这个 BroastcastReceive 来启动servicepc 端命令:viewplaincopytoclipboardprint?1.Runtime.getRuntime().exec(2.adbshellambroadcast-aNotifyServiceStart);Runtime.getRu

4、ntime().exec(adbshellambroadcast-aNotifyServiceStart);illandroid 端的代码:ServiceBroadcastReceiver.javaviewplaincopytoclipboardprint?1.packagecom.otheri.service;2.3.importandroid.content.BroadcastReceiver;4.importandroid.content.Context;5.importandroid.content.Intent;6.importandroid.util.Log;7.8.publicc

5、lassServiceBroadcastReceiverextendsBroadcastReceiver9.privatestaticStringSTART_ACTION=NotifyServiceStart;10.privatestaticStringSTOP_ACTION=NotifyServiceStop;11.12.Override13.publicvoidonReceive(Contextcontext,Intentintent)Log.d(androidService.TAG,Thread.currentThread().getName()+14.15.+ServiceBroadc

6、astReceiveronReceive);16.17.Stringaction=intent.getAction();18.if(START_ACTION.equalsIgnoreCase(action)19.context.startService(newIntent(context,androidService.class);20.21.Log.d(androidService.TAG,Thread.currentThread().getName()+-22.+ServiceBroadcastReceiveronReceivestartend);23.elseif(STOP_ACTION

7、.equalsIgnoreCase(action)24.context.stopService(newIntent(context,androidService.class);25.Log.d(androidService.TAG,Thread.currentThread().getName()+-26.+ServiceBroadcastReceiveronReceivestopend);0.packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Cont

8、ext;importandroid.content.Intent;彘importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroad蠲privatestaticStringSTART_ACTION=NotifprivatestaticStringSTOP_ACTION=Notify踮图,Override理堀publicvoidonReceive(Contextcontext,Inte机翻Log.d(androidService.TAG,Thread.cu+ServiceBroadcast,明Stringaction=i

9、ntent.getAction();if(START_ACTION.equalsIgnoreCase(a刀5.由于是 USB 连接,所以 socket 就可以设计为一但连接就一直联通,即在 newsocket 和开完 out,in 流后,就用个while(true)来循环 PC 端和 android 端的读和写android 的代码:viewplaincopytoclipboardprint?1.publicvoidrun()2.Log.d(androidService.TAG,Thread.currentThread().getName()+-3.+aclienthasconnectedto

10、server!);4.BufferedOutputStreamout;5.BufferedInputStreamin;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.ioThrea

11、dFlag)14.try15.if(!client.isConnected()16.break;17.18.19./*接收 PC 发来的数据*/20.Log.v(androidService.TAG,Thread.currentThread().getName()21.+-+willread.);22./*读操作命令*/23.currCMD=readCMDFromSocket(in);24.Log.v(androidService.TAG,Thread.currentThread().getName()25.+-+*currCMD=+currCMD);26.27./*根据命令分别处理数据*/2

12、8.if(currCMD.equals(1)29.out.write(OK”.getBytes();30.out.flush();31.elseif(currCMD.equals(2)32.out.write(OK.getBytes();33.out.flush();34.elseif(currCMD.equals(3)35.out.write(OK.getBytes();36.out.flush();37.elseif(currCMD.equals(4)38./*准备接收文件数据*/39.try40.out.write(servicereceiveOK.getBytes();41.out.f

13、lush();42.catch(lOExceptione)43.e.printStackTrace();44.45.46./*接收文件数据,4 字节文件长度,4 字节文件格式,其后是文件数据*/filebytes=receiveFileFromSocket(in,out,filelength,fileformat);/Log.v(Service139.TAG,receivedata=+newtryFilefile=FileHelper.newFile(R0013340.JPG);filebytes.length);catch(IOExceptione)elseif(currCMD.equals

14、(exit)Log.e(androidService.TAG,Thread.currentThread().getName()+readwriteerror111111);Log.e(androidService.TAG,Thread.currentThread().getName()+readwriteerror222222);47.bytefilelength=newbyte4;48.bytefileformat=newbyte4;49.bytefilebytes=null;50.51./*从 socket 流中读取完整文件数据*/63.e.printStackTrace();64.66.

15、67.68.catch(Exceptione)69./try70./out.write(error.getBytes(utf-8);71./out.flush();72./catch(IOExceptione1)73./e1.printStackTrace();74./84.e.printStackTrace();85.finally5.56./String(filebytes);57.58./*生成文件*/59.60.FileHelper.writeFile(file,filebytes,0,8.79.out.close();80.i

16、n.close();81.catch(Exceptione)82.83.87.if(client!=null)88.Log.v(androidService.TAG,Thread.currentThread().getName()89.+-+client.close();90.client.close();91.92.catch(IOExceptione)93.Log.e(androidService.TAG,Thread.currentThread().getName()94.+-+readwriteerror333333);95.e.printStackTrace();96.97.publ

17、icvoidrun()Log.d(androidService.TAG,Thread.cu+aclienthasconBufferedOutputStreamout;BufferedInputStreamin;try/*PC 端发来的数据 msg*/StringcurrCMD=;out=newBufferedOutputStrin=newBufferedInputStrea/testSocket();/测试 sockandroidService.ioThreadFlagwhile(androidService.ioThrtryif(!client6.如果是在 PC 端和 android 端的读

18、写操作来因为-1”是只有在 socket 关闭时才作为判断结尾。7.socket 在 out.write(bytes);时,要是数据太大时,超过 socket 的缓存,socket 自动分包发送,所以对方就一定要用循环来多次读。最好的办法就是服务器和客户端协议好,比如发文件时,先写过来一个要发送的文件的大小,然后再发送文件;对方用这个大小,来循环读取数据。android 端接收数据的代码:viewplaincopytoclipboardprint?brewhile(true)循环,这样 socket 流的结尾不好判断,不能用-1”来判断,1./*2.*功能:从 socket流中读取完整文件数据

19、3.4.*InputStreamin:socket 输入流5.6.*bytefilelength:流的前 4 个字节存储要转送的文件的字节数7.8.*bytefileformat:流的前 5-8 字节存储要转送的文件的格式(如.apk)*功能:从 socket 流中读取完整文件数据*InputStreamin:socket 输入流*bytefilelength:流白前 4 个字节存储要转送*bytefileformat:流的前 5-8 字节存储要转送*/publicstaticbytereceiveFileFromSocket(OutputStreamout,bytefibytefilebyt

20、es=null;/文件数据tryintfilelen=MyUtil.bytesTStringstrtmp=readfileout.write(strtmp.getBytes(out.flush();/*4.35.*/publicstaticbytereceiveFileFromSocket(InputStreamin,OutputStreamout,bytefilelength,bytefileformat)bytefilebytes=null;/文

21、件数据tryintfilelen=MyUtil.bytesToInt(filelength);/Stringstrtmp=readfilelengthok:+filelen;out.write(strtmp.getBytes(utf-8);out.flush();filebytes=newbytefilelen;intpos=intrcvLen=36.文件长度从 4 字节 byte转成 Int0;0;while(rcvLen=in.read(filebytes,pos,filelen-pos)pos+=rcvLen;Log.v(androidService.TAG,Thread.current

22、Thread().getName()+readfileOK:filesize=+filebytes.length);out.write(readfileok.getBytes(utf-8);out.flush();catch(Exceptione)Log.v(androidService.TAG,Thread.currentThread().getName()+receiveFileFromSocketerror);e.printStackTrace();returnfilebytes;0)8.socket 的最重要的机制就是读写采用的是阻塞的方式,如果客户端作为命令发起者,服务器端作为接收者

23、的话,只有当客户端 client 用 out.writer()写到输出流里后,即流中有数据 service 的 read 才会执行,不然就会一直停在 read()那里等数据。9.还要让服务器端可以同时连接多个 client,即服务器端用 newthread()来作数据读取操作。源码:客户端(pc 端):iCopyofJestPCClirrt,工srcJ.J(defaultparkage)jzileHelper.JavdtertPcClientjava%jtools.JavatestPcClient.javaviewplaincopytoclipboardprint?1.importjava.i

24、o.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;.InetAddress;.Socket;10. .UnknownHostException;11.12. publicclasstestPcClient13.14

25、. /*15. *paramargs16. *throwsInterruptedException17. */18. publicstaticvoidmain(Stringargs)throwsInterruptedException19. try20. Runtime.getRuntime().exec(21. adbshellambroadcast-aNotifyServiceStop);22.Thread.sleep(3000);23.Runtime.getRuntime().exec(adbforwardtcp:12580tcp:10086);24.Thread.sleep(3000)

26、;25.Runtime.getRuntime().exec(26.adbshellambroadcast-aNotifyServiceStart);27.Thread.sleep(3000);28.catch(IOExceptione3)29.e3.printStackTrace();30.31.32.Socketsocket=null;33.try34.InetAddressserverAddr=null;35.serverAddr=InetAddress.getByName();36.System.out.println(TCP1111+C:Connecting.);37

27、.socket=newSocket(serverAddr,12580);38.Stringstr=hi,wufenglong;39.System.out.println(TCP221122+C:RECEIVE);40.BufferedOutputStreamout=newBufferedOutputStream(socket41.getOutputStream();42.BufferedInputStreamin=newBufferedInputStream(socket43.getInputStream();44.BufferedReaderbr=newBufferedReader(newI

28、nputStreamReader(45.System.in);46.booleanflag=true;47.while(flag)48.System.out.print(请输入 16 的数字,退出输入 exit:);49.StringstrWord=br.readLine();/从控制台输入 1650.if(strWord.equals(T)51.out.write(1.getBytes();52.out.flush();53.System.out.println(1finishsendingthedata);54.StringstrFormsocket=readFromSocket(in);

29、55.System.out.println(thedatasentbyserveris:/r/n56.+strFormsocket);57.System.out58.println(=);59.elseif(strWord.equals(2)60.out.write(2.getBytes();System.out.println(2finishsendingthedata);StringstrFormsocket=readFromSocket(in);System.out.println(thedatasentbyserveris:/r/n+strFormsocket);System.out.

30、println(=);elseif(strWord.equals(3)out.write(3.getBytes();out.flush();System.out.println(3finishsendingthedata);StringstrFormsocket=readFromSocket(in);System.out.println(thedatasentbyserveris:/r/n+strFormsocket);System.out.println(=);elseif(strWord.equals(4)/*发送命令*/out.write(4.getBytes();out.flush()

31、;System.out.println(sendfilefinishsendingtheCMD:);/*服务器反馈:准备接收*/StringstrFormsocket=readFromSocket(in);System.out.println(servicereadyreceicedata:UPDATE_CONTACTS:+strFormsocket);bytefilebytes=FileHelper.readFile(R0013340.JPG);System.out.println(filesize=+filebytes.length);/*将整数转成 4 字节 byte 数组*/bytef

32、ilelength=newbyte4;filelength=ToByte(filebytes.length);/*将.apk 字符串转成 4 字节 byte 数组*/bytefileformat=null;fileformat=.apk.getBytes();System.out.println(fileformatlength=+fileformat.length);/*字节流中前 4 字节为文件长度,4 字节文件格式,以后是文件流*/*注意如果 write 里的 byte超过 socket 的缓存,系统自动分包写过去,所以对方要循环写*/out.write(filelen

33、gth);8.99.Stringstrok1=readFromSocket(in);System.out.println(servicereceivefilelength:+strok1);/out.write(fileformat);/out.flush();/Stringstrok2=readFromSocket(in);/System.out.println(service

34、receivefileformat:+/strok2);System.out.println(writedatatoandroid);out.write(filebytes);out.flush();System.out.println(*);/*服务器反馈:接收成功*/Stringstrread=readFromSocket(in);System.out.println(senddatasuccess:+strread);System.out.println(=);elseif(strWord.equalsIgnoreCase(EXIT)out.write(EXIT.getBytes();o

35、ut.flush();System.out.println(EXITfinishsendingthedata);StringstrFormsocket=readFromSocket(in);System.out.println(thedatasentbyserveris:/r/n+strFormsocket);flag=false;System.out.println(=);catch(UnknownHostExceptione1)System.out.println(TCP331133+ERROR:+e1.toString();catch(Exceptione2)System.out.pri

36、ntln(TCP441144+ERROR:+e2.toString();finallytryif(socket!=null)socket.close();System.out.println(socket.close();141.catch(lOExceptione)0042.System

37、.out.println(TCP5555+ERROR:+e.toString();46.147./*从 InputStream 流中读数据*/148.publicstaticStringreadFromSocket(InputStreamin)149.intMAX_BUFFER_BYTES=4000;150.Stringmsg=;151.bytetempbuffer=newbyteMAX_BUFFER_BYTES;152.numReadedBytes=in.read(tempbuffer,0,tempbuffer.length);154.msg=n

38、ewString(tempbuffer,0,numReadedBytes,utf-8);155.156.tempbuffer=null;157.catch(Exceptione)158.e.printStackTrace();159.160./Log.v(Service139.TAG,msg=+msg);161.returnmsg;162.163.importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutp

39、utStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.InetAddress;.Socket;.UnknownHostException;publicclasstestPcClient/*paramargs*throwsInterruptedException*/publicstaticvoidmain(String口args)throandroid 服务器端:1产src3com,otheri,serviceL也androidSenriceJava|JiServ

40、iceBroadcastReceiwerjaval?出ThreadReadWriteriOSockdjava#田com.othen,util口出FilHelper.java中J|MyUtil.java主类 androidService.javaviewplaincopytoclipboardprint?1.packagecom.otheri.service;2.3.importjava.io.File;4.importjava.io.IOException;.ServerSocket;.Socket;7.8.importandroid.app.Service;9.importandroid.c

41、ontent.BroadcastReceiver;10.importandroid.content.Context;11.importandroid.content.Intent;12.importandroid.content.IntentFilter;13.importandroid.os.IBinder;14.importandroid.util.Log;15.16./*17.*设置:android 手机18.*19.*20.*/21.publicclassandroidServiceextendsService22.publicstaticfinalStringTAG=TAG;23.p

42、ublicstaticBooleanmainThreadFlag=true;24.publicstaticBooleanioThreadFlag=true;25.ServerSocketserverSocket=null;26.finalintSERVER_PORT=10086;27.FiletestFile;28.privatesysBroadcastReceiversysBR;29.30.Override31.publicvoidonCreate()32.super.onCreate();33.Log.v(TAG,Thread.currentThread().getName()+-+onC

43、reate);34./*创建内部类 sysBroadcastReceiver 并注册 registerReceiver*/35.sysRegisterReceiver();36.newThread()37.publicvoidrun()38.doListen();39.;40.start();41.42.43.privatevoiddoListen()44.Log.d(TAG,Thread.currentThread().getName()+-45.+”doListen()START);46.serverSocket=null;47.try48.Log.d(TAG,Thread.current

44、Thread().getName()+-49.+doListen()newserverSocket);50.serverSocket=newServerSocket(SERVER_PORT);51.52.booleanmainThreadFlag=true;53.while(mainThreadFlag)54.Log.d(TAG,Thread.currentThread().getName()+-55.+doListen()listen);56.57.Socketclient=serverSocket.accept();58.59.newThread(newThreadReadWriterIO

45、Socket(this,client).start();60.61.catch(IOExceptione1)62.Log.v(androidService.TAG,Thread.currentThread().getName()63.+newserverSocketerror);64.e1.printStackTrace();65.67.68./*创建内部类 sysBroadcastReceiver 并注册 registerReceiver*/69.privatevoidsysRegisterReceiver()70.Log.v(TAG,Thread.currentThread().getNa

46、me()+-71.+sysRegisterReceiver);72.sysBR=newsysBroadcastReceiver();73./*注册 BroadcastReceiver*/74.IntentFilterfilter1=newIntentFilter();75./*新的应用程序被安装到了设备上的广播*/76.filter1.addAction(ent.action.PACKAGE_ADDED);77.filter1.addDataScheme(package);78.filter1.addAction(ent.action.PACKAGE

47、_REMOVED);79.filter1.addDataScheme(package);80.registerReceiver(sysBR,filterl);81.82.83./*内部类:BroadcastReceiver 用于接收系统事件*/84.privateclasssysBroadcastReceiverextendsBroadcastReceiver85.86.Override87.publicvoidonReceive(Contextcontext,Intentintent)88.Stringaction=intent.getAction();89.if(action.equals

48、IgnoreCase(ent.action.PACKAGE_ADDED)90./ReadInstalledAPP();91.elseif(action92.equalsIgnoreCase(ent.action.PACKAGE_REMOVED)93./ReadInstalledAPP();94.95.Log.v(TAG,Thread.currentThread().getName()+-96.+sysBroadcastReceiveronReceive);00.Override101.publicvoidonDestroy()10

49、2.super.onDestroy();103.104./关闭线程105.mainThreadFlag=false;107./关闭服务器108.try109.Log.v(TAG,Thread.currentThread().getName()+-110.+serverSocket.close();111.serverSocket.close();112.catch(IOExceptione)113.e.printStackTrace();114.115.Log.v(TAG,Thread.currentThread().getName()+-117.118.119.Override120.pub

50、licvoidonStart(Intentintent,intstartId)121.Log.d(TAG,Thread.currentThread().getName()+-+122.super.onStart(intent,startId);26.Override127.publicIBinderonBind(Intentarg0)128.Log.d(TAG,onBind);129.returnnull;130.131.132.packagecom.otheri.service;importjava.io.File;importjava.io.IOException

51、;.ServerSocket;.Socket;importandroid.app.Service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.IBinder;importandroid.util.Log;/*设置:android 手机*116.u*onDestroy*”);onStart();用于接收 PC 发来的 Broastcast 并

52、启动主类 service 的ServiceBroadcastReceiver.javaviewplaincopytoclipboardprint?1.packagecom.otheri.service;2.3.importandroid.content.BroadcastReceiver;4.importandroid.content.Context;5.importandroid.content.Intent;6.importandroid.util.Log;7.8.publicclassServiceBroadcastReceiverextendsBroadcastReceiver9.pr

53、ivatestaticStringSTART_ACTION=NotifyServiceStart;10.privatestaticStringSTOP_ACTION=NotifyServiceStop;11.12.Override13.publicvoidonReceive(Contextcontext,Intentintent)14.Log.d(androidService.TAG,Thread.currentThread().getName()+-15.+ServiceBroadcastReceiveronReceive);16.17.Stringaction=intent.getActi

54、on();18.if(START_ACTION.equalsIgnoreCase(action)19.context.startService(newIntent(context,androidService.class);20.21.Log.d(androidService.TAG,Thread.currentThread().getName()+-22.+ServiceBroadcastReceiveronReceivestartend);23.elseif(STOP_ACTION.equalsIgnoreCase(action)24.context.stopService(newInte

55、nt(context,androidService.class);25.Log.d(androidService.TAG,Thread.currentThread().getName()+-26.+ServiceBroadcastReceiveronReceivestopend);0.packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log

56、;publicclassServiceBroadcastReceiverextendsBroadprivatestaticStringSTART_ACTION=NotifprivatestaticStringSTOP_ACTION=NotifyOverridepublicvoidonReceive(Contextcontext,InteLog.d(androidService.TAG,Thread.cu+ServiceBroadcastStringaction=intent.getAction();if(START_ACTION.equalsIgnoreCase(a用于新 socket 连接的

57、读写线程类 ThreadReadWriterIOSocket.javaviewplaincopytoclipboardprint?1.packagecom.otheri.service;2.3.importjava.io.BufferedInputStream;4.importjava.io.BufferedOutputStream;5.importjava.io.ByteArrayOutputStream;6.importjava.io.File;7.importjava.io.IOException;8.importjava.io.InputStream;9.importjava.io.O

58、utputStream;.Socket;11.12.importandroid.content.Context;13.importandroid.util.Log;14.15.importcom.otheri.util.FileHelper;16.importcom.otheri.util.MyUtil;17.18./*19.*功能:用于 socket 的交互20.*21.*authorwufenglong22.*23.*/24.publicclassThreadReadWriterIOSocketimplementsRunnable25.privateSocketclient;26.priv

59、ateContextcontext;27.28.ThreadReadWriterIOSocket(Contextcontext,Socketclient)29.30.this.client=client;31.this.context=context;32.33.34.Override35.publicvoidrun()36.Log.d(androidService.TAG,Thread.currentThread().getName()+-37.+aclienthasconnectedtoserver!);38.BufferedOutputStreamout;39.BufferedInput

60、Streamin;40.try41./*PC 端发来的数据 msg*/42.StringcurrCMD=;43.out=newBufferedOutputStream(client.getOutputStream();44.in=newBufferedInputStream(client.getInputStream();45./testSocket();/测试 socket 方法46.androidService.ioThreadFlag=true;47.while(androidService.ioThreadFlag)48.try49.if(!client.isConnected()50

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论