PC客户端与Android服务端的Socket同步通信_第1页
PC客户端与Android服务端的Socket同步通信_第2页
PC客户端与Android服务端的Socket同步通信_第3页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

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

文档简介

1、PC客户端与Android服务端的Socket同步通信需求:1. 一个android端的service后台运行的程序,作为socket的服务器端;用于接收Pcclient端发来的命令,来处理数据后,把结果发给PCclient2. PC端程序,作为socket的客户端,用于给android手机端发操作命令难点分析:1. 手机一定要有adb模式,即插上USB线时马上提示的对话框选adb。好多对手机的操作都可以用adb直接作。不过,我发现LGGW880就没有,要去下载个2. android默认手机端的IP为“”3. 要想联通PC与android手机的sokcet,一定要用adbfo

2、rward来作下端口转发才能连上socket.viewplaincopytoclipboardprint?Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");Thread.sleep(3000);Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");Thread.sleep(3000);android端的service程序Install到手机上容易,但是还要有方法来从PC的client端来启动手机上的service,这个办法可以通

3、过PC端adb命令来发一个Broastcast,手机端再写个接收BroastcastReceive来接收这个Broastcast,在这个BroastcastReceive来启动servicepc端命令:viewplaincopytoclipboardprint?Runtime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStart");Runtime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStart");android端的代码

4、:ServiceBroadcastReceiver.javaviewplaincopytoclipboardprint?packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiverprivatestaticStringSTART_ACTION=&

5、quot;NotifyServiceStart"privatestaticStringSTOP_ACTION="NotifyServiceStop"OverridepublicvoidonReceive(Contextcontext,Intentintent)Log.d(androidService.TAG,Thread.currentThread().getName()+"->"+"ServiceBroadcastReceiveronReceive");Stringaction=intent.getAction();

6、if(START_ACTION.equalsIgnoreCase(action)context.startService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+">+"ServiceBroadcastReceiveronReceivestartend");elseif(STOP_ACTION.equalsIgnoreCase(action)context.stopService(newIntent(co

7、ntext,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+">+"ServiceBroadcastReceiveronReceivestopend");packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;p

8、ublicclassServiceBroadcastReceiverextendsBroadcastReceiverprivatestaticStringSTART_ACTION="NotifyServiceStart"privatestaticStringSTOP_ACTION="NotifyServiceStop"OverridepublicvoidonReceive(Contextcontext,Intentintent)Log.d(androidService.TAG,Thread.currentThread().getName()+"

9、->+"ServiceBroadcastReceiveronReceive");Stringaction=intent.getAction();if(START_ACTION.equalsIgnoreCase(action)context.startService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+"->"+"ServiceBroadcastReceiveronReceiv

10、estartend");elseif(STOP_ACTION.equalsIgnoreCase(action)context.stopService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+"->"+"ServiceBroadcastReceiveronReceivestopend");4. 由于是USB连接,所以socket就可以设计为一但连接就一直联通,即在newsocket和开完

11、out,in流后,就用个while(true)来循环PC端和android端的读和写android的代码:viewplaincopytoclipboardprint?publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+"->"+"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PC端发来的数据msg*/StringcurrCMD="

12、"out=newBufferedOutputStream(client.getOutputStream();in=newBufferedInputStream(client.getInputStream();/testSocket();/测试socket方法androidService.ioThreadFlag=true;while(androidService.ioThreadFlag)tryif(!client.isConnected()break;/*接收PC发来的数据*/Log.v(androidService.TAG,Thread.currentThread().getNa

13、me()+"一>"+"willread.");/*读操作命令*/currCMD=readCMDFromSocket(in);Log.v(androidService.TAG,Thread.currentThread().getName()+"->"+"*currCMD="+currCMD);/*根据命令分别处理数据*/if(currCMD.equals("1”)out.write("OK".getBytes();out.flush();elseif(currCMD.equa

14、ls("2”)out.write("OK”.getBytes();out.flush();elseif(currCMD.equals("3”)out.write("OK”.getBytes();out.flush();elseif(currCMD.equals("4”)/*准备接收文件数据*/tryout.write("servicereceiveOK”.getBytes();out.flush();catch(IOExceptione)e.printStackTrace();/*接收文件数据,4字节文件长度,4字节文件格式,其后是文

15、件数据*/bytefilelength=newbyte4;bytefileformat=newbyte4;bytefilebytes=null;/*从socket流中读取完整文件数据*/filebytes=receiveFileFromSocket(in,out,filelength,fileformat);/Log.v(Service139.TAG,"receivedata="+new/String(filebytes);try/*生成文件*/Filefile=FileHelper.newFile("R0013340.JPG”);FileHelper.write

16、File(file,filebytes,0,filebytes.length);catch(IOExceptione)e.printStackTrace();elseif(currCMD.equals("exit")catch(Exceptione)/try/out.write("error”.getBytes("utf-8”);/out.flush();/catch(IOExceptione1)/e1.printStackTrace();/Log.e(androidService.TAG,Thread.currentThread().getName()

17、+"->"+"readwriteerror111111");out.close();in.close();catch(Exceptione)Log.e(androidService.TAG,Thread.currentThread().getName()+"->"+"readwriteerror222222");e.printStackTrace();finallytryif(client!=null)Log.v(androidService.TAG,Thread.currentThread().get

18、Name()+"->"+"client.close()");client.close();catch(IOExceptione)Log.e(androidService.TAG,Thread.currentThread().getName()+"->"+"readwriteerror333333");e.printStackTrace();publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+"->

19、;"+"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PC端发来的数据msg*/StringcurrCMD=""out=newBufferedOutputStream(client.getOutputStream();in=newBufferedInputStream(client.getInputStream();/testSocket();/测试socket方法androidService.ioThreadFlag=true

20、;while(androidService.ioThreadFlag)tryif(!client.isConnected()break;/*接收PC发来的数据*/Log.v(androidService.TAG,Thread.currentThread().getName()+"一>"+"willread.");/*读操作命令*/currCMD=readCMDFromSocket(in);Log.v(androidService.TAG,Thread.currentThread().getName()+"->"+"

21、;*currCMD="+currCMD);/*根据命令分别处理数据*/if(currCMD.equals("1”)out.write("OK".getBytes();out.flush();elseif(currCMD.equals("2”)out.write("OK”.getBytes();out.flush();elseif(currCMD.equals("3”)out.write("OK”.getBytes();out.flush();elseif(currCMD.equals("4”)/*准备接收

22、文件数据*/tryout.write("servicereceiveOK”.getBytes();out.flush();catch(IOExceptione)e.printStackTrace();/*接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据*/byte口filelength=newbyte4;bytefileformat=newbyte4;bytefilebytes=null;/*从socket流中读取完整文件数据*/filebytes=receiveFileFromSocket(in,out,filelength,fileformat);/Log.v(Ser

23、vice139.TAG,"receivedata="+new/String(filebytes);try/*生成文件*/Filefile=FileHelper.newFile("R0013340.JPG”);FileHelper.writeFile(file,filebytes,0,filebytes.length);catch(IOExceptione)e.printStackTrace();elseif(currCMD.equals("exit")catch(Exceptione)/try/out.write("error”.ge

24、tBytes("utf-8”);/out.flush();/catch(IOExceptione1)/e1.printStackTrace();/Log.e(androidService.TAG,Thread.currentThread().getName()+"->"+"readwriteerror111111");out.close();in.close();catch(Exceptione)Log.e(androidService.TAG,Thread.currentThread().getName()+"->&qu

25、ot;+"readwriteerror222222");e.printStackTrace();finallytryif(client!=null)Log.v(androidService.TAG,Thread.currentThread().getName()+"->"+"client.close()");client.close();catch(IOExceptione)Log.e(androidService.TAG,Thread.currentThread().getName()+"->"+&q

26、uot;readwriteerror333333");e.printStackTrace();5. 如果是在PC端和android端的读写操作来while(true)(循环,这样socket流的结尾不好判断,不能用-T'来判断,因为-T是只有在socket关闭时才作为判断结尾。socket在out.write(bytes);时,要是数据太大时,超过socket的缓存,socket自动分包发送,所以对方就一定要用循环来多次读。最好的办法就是服务器和客户端协议好,比如发文件时,先写过来一个要发送的文件的大小,然后再发送文件;对方用这个大小,来循环读取数据。android端接收数据

27、的代码viewplaincopytoclipboardprint?/*功能:从socket流中读取完整文件数据* InputStreamin:socket输入流* bytefilelength:流的前4个字节存储要转送的文件的字节数*.apk)* byte口fileformat:流的前5-8字节存储要转送的文件的格式(如*/publicstaticbytereceiveFileFromSocket(InputStreamin,OutputStreamout,bytefilelength,bytefileformat)(bytefilebytes=null;/文件数据try(intfilelen

28、=MyUtil.bytesToInt(filelength);/文件长度从4字节byte转成IntStringstrtmp="readfilelengthok:"+filelen;out.write(strtmp.getBytes("utf-8”);out.flush();filebytes=newbytefilelen;intpos=0;intrcvLen=0;while(rcvLen=in.read(filebytes,pos,filelen-pos)>0)(pos+=rcvLen;Log.v(androidService.TAG,Thread.curr

29、entThread().getName()+"->"+"readfileOK:filesize="+filebytes.length);out.write("readfileok”.getBytes("utf-8”);out.flush();catch(Exceptione)(Log.v(androidService.TAG,Thread.currentThread().getName()+"->"+"receiveFileFromSocketerror");e.printStack

30、Trace();returnfilebytes;*功能:从socket流中读取完整文件数据* InputStreamin:socket输入流* byte口filelength:流的前4个字节存储要转送的文件的字节数* byte口fileformat:流的前5-8字节存储要转送的文件的格式(如.apk)*/publicstaticbytereceiveFileFromSocket(InputStreamin,OutputStreamout,bytefilelength,bytefileformat)bytefilebytes=null;/文件数据tryintfilelen=MyUtil.byte

31、sToInt(filelength);/文件长度从4字节byte转成IntStringstrtmp="readfilelengthok:"+filelen;out.write(strtmp.getBytes("utf-8");out.flush();filebytes=newbytefilelen;intpos=0;intrcvLen=0;while(rcvLen=in.read(filebytes,pos,filelen-pos)>0)pos+=rcvLen;Log.v(androidService.TAG,Thread.currentThrea

32、d().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();r

33、eturnfilebytes;socket的最重要的机制就是读写采用的是阻塞的方式,如果客户端作为命令发起者,服务器端作为接收者的话,只有当客户端client用out.writer()写到输出流里后,即流中有数据service的read才会执行,不然就会一直停在read()那里等数据。6. 还要让服务器端可以同时连接多个client,即服务器端用newthread()来作数据读取操作。源码:客户端(pc端):testPcClient.javaviewplaincopytoclipboardprint?importjava.io.BufferedInputStream;importjava.io

34、.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.InetAddress;.Socket;.UnknownHostException;publicclasstestPcClient/* paramargs* throwsInterruptedException*/publicstaticvoidmain(

35、Stringargs)throwsInterruptedExceptiontryRuntime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStop");Thread.sleep(3000);Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");Thread.sleep(3000);Runtime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStart"

36、;);Thread.sleep(3000);catch(IOExceptione3)e3.printStackTrace();Socketsocket=null;try(InetAddressserverAddr=null;serverAddr=InetAddress.getByName("");System.out.println("TCP1111"+"C:Connecting.");socket=newSocket(serverAddr,12580);Stringstr="hi,wufenglong&q

37、uot;System.out.println("TCP221122"+"C:RECEIVE");BufferedOutputStreamout=newBufferedOutputStream(socket.getOutputStream();BufferedInputStreamin=newBufferedInputStream(socket.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in);booleanflag=true;while(

38、flag)(System.out.print("请输入16的数字,退出输入exit:");StringstrWord=br.readLine();/从控制台输入16if(strWord.equals("1")(out.write("1".getBytes();out.flush();System.out.println("1finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasen

39、tbyserveris:rn"+strFormsocket);System.out.println("=");elseif(strWord.equals("2")(out.write("2”.getBytes();out.flush();System.out.println("2finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+st

40、rFormsocket);System.out.println("=");elseif(strWord.equals("3")(out.write("3”.getBytes();out.flush();System.out.println("3finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+strFormsocket);System.out

41、.println("=");elseif(strWord.equals("4”)/*发送命令*/out.write("4”.getBytes();out.flush();System.out.println("sendfilefinishsendingtheCMD:");/*服务器反馈:准备接收*/StringstrFormsocket=readFromSocket(in);System.out.println("servicereadyreceicedata:UPDATE_CONTACTS:"+strFormso

42、cket);bytefilebytes=FileHelper.readFile("R0013340.JPG”);System.out.println("filesize="+filebytes.length);/*将整数转成4字节byte数组*/bytefilelength=newbyte4;filelength=ToByte(filebytes.length);/*将.apk字符串转成4字节byte数组*/bytefileformat=null;fileformat=".apk”.getBytes();System.out.print

43、ln("fileformatlength="+fileformat.length);/*字节流中前4字节为文件长度,4字节文件格式,以后是文件流*/*注意如果write里的byte超过socket的缓存,系统自动分包写过去,所以对方要循环写完*/out.write(filelength);out.flush();Stringstrok1=readFromSocket(in);System.out.println("servicereceivefilelength:"+strok1);/out.write(fileformat);/out.flush();

44、/Stringstrok2=readFromSocket(in);/System.out.println("servicereceivefileformat:"+/strok2);System.out.println("writedatatoandroid");out.write(filebytes);out.flush();System.out.println("*");/*服务器反馈:接收成功*/Stringstrread=readFromSocket(in);System.out.println("senddatasu

45、ccess:"+strread);System.out.println("=:=”);elseif(strWord.equalsIgnoreCase("EXIT")out.write("EXIT”.getBytes();out.flush();System.out.println("EXITfinishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+s

46、trFormsocket);flag=false;System.out.println("=:=");catch(UnknownHostExceptione1)System.out.println("TCP331133"+"ERROR:"+e1.toString();catch(Exceptione2)System.out.println("TCP441144"+"ERROR:"+e2.toString();finallytryif(socket!=null)socket.close();Sys

47、tem.out.println("socket.close()");catch(IOExceptione)System.out.println("TCP5555”+"ERROR:"+e.toString();/*从InputStream流中读数据*/publicstaticStringreadFromSocket(InputStreamin)intMAX_BUFFER_BYTES=4000;Stringmsg=""bytetempbuffer=newbyteMAX_BUFFER_BYTES;tryintnumReadedBy

48、tes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"utf-8");tempbuffer=null;catch(Exceptione)e.printStackTrace();/Log.v(Service139.TAG,"msg="+msg);returnmsg;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.Buffe

49、redReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.InetAddress;.Socket;.UnknownHostException;publicclasstestPcClient/* paramargs* throwsInterruptedException*/publicstaticvoidmain(Stringargs)throwsInterruptedExceptiontryR

50、untime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStop");Thread.sleep(3000);Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");Thread.sleep(3000);Runtime.getRuntime().exec("adbshellambroadcast-aNotifyServiceStart");Thread.sleep(3000);catch(IOExceptione3

51、)e3.printStackTrace();Socketsocket=null;tryInetAddressserverAddr=null;serverAddr=InetAddress.getByName("");System.out.println("TCP1111"+"C:Connecting.");socket=newSocket(serverAddr,12580);Stringstr="hi,wufenglong”;System.out.println("TCP221122"+&

52、quot;C:RECEIVE");BufferedOutputStreamout=newBufferedOutputStream(socket.getOutputStream();BufferedInputStreamin=newBufferedInputStream(socket.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in);booleanflag=true;while(flag)System.out.print("请输入16的数字,退出输入exit:

53、");StringstrWord=br.readLine();/从控制台输入16if(strWord.equals("1")(out.write("1".getBytes();out.flush();System.out.println("1finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+strFormsocket);System.out.

54、println("=");elseif(strWord.equals("2")(out.write("2”.getBytes();out.flush();System.out.println("2finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+strFormsocket);System.out.println("=");

55、elseif(strWord.equals("3")(out.write("3”.getBytes();out.flush();System.out.println("3finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+strFormsocket);System.out.println("=");elseif(strWord.equals(&

56、quot;4")(/*发送命令*/out.write("4”.getBytes();out.flush();System.out.println("sendfilefinishsendingtheCMD:");/*服务器反馈:准备接收*/StringstrFormsocket=readFromSocket(in);System.out.println("servicereadyreceicedata:UPDATE_CONTACTS:"+strFormsocket);bytefilebytes=FileHelper.readFile(&

57、quot;R0013340.JPG”);System.out.println("filesize="+filebytes.length);/*将整数转成4字节byte数组*/bytefilelength=newbyte4;filelength=ToByte(filebytes.length);/*将.apk字符串转成4字节byte数组*/bytefileformat=null;fileformat=".apk”.getBytes();System.out.println("fileformatlength="+fileform

58、at.length);/*字节流中前4字节为文件长度,4字节文件格式,以后是文件流*/*注意如果write里的byte超过socket的缓存,系统自动分包写过去,所以对方要循环写完*/out.write(filelength);out.flush();Stringstrok1=readFromSocket(in);System.out.println("servicereceivefilelength:"+strok1);/out.write(fileformat);/out.flush();/Stringstrok2=readFromSocket(in);/System.

59、out.println("servicereceivefileformat:"+/strok2);System.out.println("writedatatoandroid");out.write(filebytes);out.flush();System.out.println("*");/*服务器反馈:接收成功*/Stringstrread=readFromSocket(in);System.out.println("senddatasuccess:"+strread);System.out.println(

60、"=");elseif(strWord.equalsIgnoreCase("EXIT")out.write("EXIT".getBytes();out.flush();System.out.println("EXITfinishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:rn"+strFormsocket);flag=false;System.o

61、ut.println("=");catch(UnknownHostExceptione1)System.out.println("TCP331133"+"ERROR:"+e1.toString();catch(Exceptione2)System.out.println("TCP441144"+"ERROR:"+e2.toString();finallytryif(socket!=null)socket.close();System.out.println("socket.close(

62、)");catch(IOExceptione)System.out.println("TCP5555”+"ERROR:"+e.toString();/*从InputStream流中读数据*/publicstaticStringreadFromSocket(InputStreamin)intMAX_BUFFER_BYTES=4000;Stringmsg=""bytetempbuffer=newbyteMAX_BUFFER_BYTES;tryintnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"

温馨提示

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

评论

0/150

提交评论