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

下载本文档

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

文档简介

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

2、roid手机的sokcet,一定要用adb forward来作下端口转发才能连 上 socket.view pla in copy to clipboardpri nt?Run time.getR un time().exec("adb forward tcp:12580 tcp:10086");Thread.sleep(3000);Run time.getR un time().exec("adb forward tcp:12580 tcp:10086");Thread.sleep(3000);4. a ndroid端的service程序In stal

3、l到手机上容易,但是还要有方法来从PC的clie nt端来启动手机上的 service,这个办法可以通过 PC端adb命令来发一个 Broastcast ,手机 端再写个接收 BroastcastReceive来接收这个 Broastcast,在这个 BroastcastReceive来启动 servicepc端命令:view pla in copy to clipboardpri nt?Run time.getR un time().exec("adb shell am broadcast -a NotifyServiceStart");Run time.getR un

4、time().exec("adb shell am broadcast -a NotifyServiceStart");an droid 端的代码:ServiceBroadcastReceiver.javaview pla in copy to clipboardpri nt?package com.otheri.service;import an droid.c onten t.BroadcastReceiver;import an droid.c onten t.C on text;import an droid.c onten t.I ntent;import an

5、droid.util.Log;public class ServiceBroadcastReceiver exte nds BroadcastReceiver private static Stri ng START_ACTION = "NotifyServiceStart"private static Stri ng STOP_ACTION = "NotifyServiceStop"Overridepublic void on Receive(C on text con text, Intent intent) Log.d(androidService

6、.TAG , Thread.currentThread().getName() + ">"+ "ServiceBroadcastReceiver on Receive");String action = inten t.getAct ion();if (START_ACTION.equalslg noreCase(actio n) con text.startService (new Inten t(c on text, an droidService.class);Log.d(androidService.TAG , Thread.current

7、Thread().getName() + ">"+ "ServiceBroadcastReceiver on Receive start en d"); else if (STOP_ACTION.equalslg no reCase(actio n) con text.stopService (new Inten t(c on text, an droidService.class);Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ &qu

8、ot;ServiceBroadcastReceiver on Receive stop en d");package com.otheri.service;import an droid.c onten t.BroadcastReceiver;import an droid.c onten t.C on text;import an droid.c onten t.I ntent;import an droid.util.Log;public class ServiceBroadcastReceiver exte nds BroadcastReceiver private stati

9、c Stri ng START_ACTION = "NotifyServiceStart"private static Stri ng STOP_ACTION = "NotifyServiceStop"Overridepublic void on Receive(C on text con text, Intent intent) Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ "ServiceBroadcastReceiver on

10、 Receive");String action = inten t.getAct ion();if (START_ACTION.equalslg noreCase(actio n) con text.startService (new Inten t(c on text, an droidService.class);Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ "ServiceBroadcastReceiver on Receive start en d&q

11、uot;); else if (STOP_ACTION.equalsIg noreCase(actio n) con text.stopService (new Inten t(c on text, an droidService.class);Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ "ServiceBroadcastReceiver on Receive stop en d");5. 由于是USB连接,所以socket就可以设计为一但连接就一直联通,即在

12、new socket和开完out,in流后,就用个 while(true)来循环PC端和an droid端的读和写an droid的代码:view pla in copy to clipboardpri nt?public void run() Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ "a clie nt has conn ected to server!");BufferedOutputStream out;BufferedI nputStream in

13、;try /* PC端发来的数据 msg */Stri ng currCMD =""out = new BufferedOutputStream(clie nt.getOutputStream();in = new BufferedI nputStream(clie nt.getl nputStream();/ testSocket(); 测试 socket 方法an droidService.ioThreadFlag = true;while (an droidService.ioThreadFlag) try if (!clie nt.isCo nn ected() b

14、reak;/*接收PC发来的数据*/Log.v(androidService.TAG , Thread.currentThread().getName()+ "->" + "will read”);/*读操作命令*/currCMD = readCMDFromSocket(i n);Log.v(androidService.TAG , Thread.currentThread().getName()+ "->" + "*currCMD = " + currCMD);/*根据命令分别处理数据*/if (currCMD

15、.equals("1") out.write("OK".getBytes();out.flush(); else if (currCMD.equals("2") out.write("OK".getBytes();out.flush(); else if (currCMD.equals("3") out.write("OK".getBytes();out.flush(); else if (currCMD.equals("4") /*准备接收文件数据*/t

16、ry out.write("service receive OK".getBytes();out.flush(); catch (IOExceptio n e) e.pri ntStackTrace();件数据*/*接收文件数据,4字节文件长度,4字节文件格式,其后是文byte filele ngth = new byte4;byte fileformat = new byte4;byte filebytes = n ull;/*从socket流中读取完整文件数据*/filebytes = receiveFileFromSocket( in, out, filele ngt

17、h,fileformat);/ Log.v(Service139.TAG , "receive data =" + new/ Stri ng(filebytes);try /*生成文件*/File file = FileHelper. newFile("R0013340.JPG");FileHelper.writeFile(file, filebytes, 0,filebytes .len gth); catch (IOExceptio n e) e.pri ntStackTrace(); else if (currCMD.equals("ex

18、it") catch (Exceptio n e) / try / out.write("error".getBytes("utf-8");/ out.flush();/ catch (IOException e1) / e1.pri ntStackTrace();/ Log.e(a ndroidService.TAG, Thread.curre ntThread().getName() + "->" + "read write error111111");out.close();in. close

19、(); catch (Excepti on e) Log.e(androidService.TAG , Thread.currentThread().getName()+ "->" + "read write error222222");e.pri ntStackTrace(); fin ally try if (clie nt != n ull) Log.v(androidService.TAG , Thread.currentThread().getName() + "->" + "clie nt.close

20、()");clie nt.close(); catch (IOExceptio n e) Log.e(androidService.TAG , Thread.currentThread().getName()+ "->" + "read write error333333");e.pri ntStackTrace();public void run() Log.d(androidService.TAG , Thread.currentThread().getName() + ">"+ "a clie n

21、t has conn ected to server!");BufferedOutputStream out;BufferedI nputStream in;try /* PC端发来的数据 msg */Stri ng currCMD =""out = new BufferedOutputStream(clie nt.getOutputStream();in = new BufferedI nputStream(clie nt.getl nputStream();/ testSocket(); 测试 socket 方法an droidService.ioThread

22、Flag = true;while (an droidService.ioThreadFlag) try if (!clie nt.isCo nn ected() break;/*接收PC发来的数据*/Log.v(androidService.TAG , Thread.currentThread().getName()+ "->" + "will read.");/*读操作命令*/currCMD = readCMDFromSocket(i n);Log.v(androidService.TAG , Thread.currentThread().ge

23、tName()+ "->" + "*currCMD = " + currCMD);/*根据命令分别处理数据*/if (currCMD.equals("1") out.write("OK".getBytes();out.flush(); else if (currCMD.equals("2") out.write("OK".getBytes();out.flush(); else if (currCMD.equals("3") out.write(&q

24、uot;OK".getBytes();out.flush(); else if (currCMD.equals("4") /*准备接收文件数据*/try out.write("service receive OK".getBytes();out.flush(); catch (IOExceptio n e) e.pri ntStackTrace();件数据*/*接收文件数据,4字节文件长度,4字节文件格式,其后是文byte filele ngth = new byte4;byte fileformat = new byte4;byte file

25、bytes = n ull;/*从socket流中读取完整文件数据*/filebytes = receiveFileFromSocket(i n, out, filele ngth,fileformat);/ Log.v(Service139.TAG , "receive data =" + new/ Stri ng(filebytes);try /*生成文件*/File file = FileHelper. newFile("R0013340.JPG");FileHelper.writeFile(file, filebytes, 0, filebyte

26、sen gth); catch (IOExceptio n e) e.pri ntStackTrace(); else if (currCMD.equals("exit") catch (Excepti on e) / try / out.write("error".getBytes("utf-8");/ out.flush();/ catch (IOException e1) / e1.pri ntStackTrace();/ Log.e(androidService.TAG , Thread.currentThread().get

27、Name() + "->" + "read write error111111");out.close();in .close(); catch (Excepti on e) Log.e(androidService.TAG , Thread.currentThread().getName()+ "->" + "read write error222222");e.pri ntStackTrace(); fin ally try if (clie nt != n ull) Log.v(androidSe

28、rvice.TAG , Thread.currentThread().getName()+ "->" + "clie nt.close()");clie nt.close(); catch (IOExceptio n e) Log.e(a ndroidService.TAG, Thread.curre ntThread().getName()+ "->" + "read write error333333");e.pri ntStackTrace();6. 如果是在PC端和an droid端的读写操作来

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

30、 in : socket 输入流* byte filelength:流的前4个字节存储要转送的文件的字节数.apk)* byte fileformat :流的前5-8字节存储要转送的文件的格式(如public static byte receiveFileFromSocket( In putStream in.Outputstream out, byte filele ngth, byte fileformat) byte filebytes = n ull;文件数据try int filelen = MyUtil.bytesTolnt(filelength);/文件长度从 4 字节 byte

31、转成 IntStri ng strtmp = "read file len gth ok:" + filele n; out.write(strtmp.getBytes("utf-8");out.flush();filebytes = new bytefilele n;int pos = 0;int rcvLe n = 0;while (rcvLe n = in. read(filebytes, pos, filele n - pos) > 0) pos += rcvLe n;Log.v(androidService.TAG , Thread.cu

32、rrentThread().getName() + "->" + "read file OK:file size=" + filebytes.le ngth);out.write("read file ok".getBytes("utf-8");out.flush(); catch (Excepti on e) Log.v(androidService.TAG , Thread.currentThread().getName()+ ">"+ "receiveFileFrom

33、Socket error");e.pri ntStackTrace(); retur n filebytes;*功能:从socket流中读取完整文件数据* InputStream in : socket 输入流* byte filelength:流的前4个字节存储要转送的文件的字节数*.apk)* byte fileformat :流的前5-8字节存储要转送的文件的格式(如*public static byte receiveFileFromSocket(l nputStream in,OutputStream out, byte filele ngth, byte fileform

34、at) byte filebytes = n ull;文件数据try int filelen = MyUtil.bytesTolnt(filelength);/文件长度从 4 字节 byte转成 IntStri ng strtmp = "read file len gth ok:" + filele n;out.write(strtmp.getBytes("utf-8");out.flush();filebytes = new bytefilele n;int pos = 0;int rcvLe n = 0;while (rcvLe n = in. re

35、ad(filebytes, pos, filele n - pos) > 0) pos += rcvLe n;Log.v(androidService.TAG , Thread.currentThread().getName() + "->" + "read file OK:file size=" + filebytes.le ngth);out.write("read file ok".getBytes("utf-8"); out.flush(); catch (Excepti on e) Log.v

36、(androidService.TAG , Thread.currentThread().getName()+ "->" + "receiveFileFromSocket error");e.pri ntStackTrace();retur n filebytes;socket的最重要的机制就是读写采用的是阻塞的方式,如果客户端作为命令发起者,服 务器端作为接收者的话,只有当客户端 client用out.writer()写到输出流里后,即流中有数据 service的read才会执行,不然就会一直停在read()那里等数据。9还要让服务器端可以同时连

37、接多个client,即服务器端用new thread()来作数据读取操作。源码:客户端(pc端):testPcClie nt.javaview pla in copy to clipboardpri nt?import java.io.Bufferedl nputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.i o.I OExcepti on;import java.i o.ln putStream

38、;import java.i o.ln putStreamReader;import java .n et.I netAddress;import java .n et.Socket;import java. net.U nknownH ostExceptio n;public class testPcClie nt * param args* throws In terruptedExcepti on*/public static void main( Stri ng args) throws In terruptedExceptio n try Run time.getR un time(

39、).exec("adb shell am broadcast -a NotifyServiceStop");Thread.sleep(3000);Run time.getR un time().exec("adb forward tcp:12580 tcp:10086");Thread.sleep(3000);Run time.getR un time().exec("adb shell am broadcast -a NotifyServiceStart");Thread.sleep(3000); catch (IOExceptio

40、n e3) e3.pri ntStackTrace();Socket socket = nu II;try In etAddress serverAddr = n ull; serverAddr = In etAddress.getByName("127.0.0.1"); System.out.pri ntl n( "TCP 1111" + "C: Co nn ecti ng."); socket = new Socket(serverAddr, 12580);String str = "hi,wufe nglon g&qu

41、ot;System.out.pri ntl n( "TCP 221122" + "C:RECEIVE");BufferedOutputStream out = new BufferedOutputStream(socket .getOutputStream();BufferedI nputStream in = new BufferedI nputStream(socket.getI nputStream();BufferedReader br = new BufferedReader( new In putStreamReader(System.i n

42、);boolea n flag = true;while (flag) System.out.print("请输入16的数字,退出输入exit:"); Stri ng strWord = br.readL in e(); 从控制台输入 16 if (strWord.equals("1") out.write("1".getBytes();out.flush();System.out.pri ntln ("1 finish sending the data"); Stri ng strFormsocket = rea

43、dFromSocket(i n); System.out.pri ntln ("the data sent by server is:r n"+ strFormsocket);System.out.pri ntln (”= "); else if (strWord.equals("2") out.write("2".getBytes();out.flush();System.out.pri ntln ("2 finish sending the data"); Stri ng strFormsocket

44、= readFromSocket(i n); System.out.pri ntln ("the data sent by server is:r n"+ strFormsocket);System.out.pri ntln (”= "); else if (strWord.equals("3") out.write("3".getBytes();out.flush();System.out.pri ntln ("3 finish sending the data"); Stri ng strFormso

45、cket = readFromSocket(i n); System.out.pri ntln ("the data sent by server is:r n"+ strFormsocket);System.out.pri ntln (”= ="); else if (strWord.equals("4") /*发送命令*/out.write("4".getBytes();out.flush();System.out.println("send file finish sending the CMD :"

46、;);/*服务器反馈:准备接收*/Stri ng strFormsocket = readFromSocket(i n);System.out.println("service ready receice data:UPDA TE_CONTACTS:"+ strFormsocket);byte filebytes = FileHelper.readFileCR0013340.JPG");System.out.pri ntl n("file size=" + filebytes .len gth);/*将整数转成4字节byte数组*/byte f

47、ilele ngth = new byte4;filele ngth = tools.i ntToByte(filebytes.le ngth);/*将.apk字符串转成4字节byte数组*/byte fileformat = nu II; fileformat = ".apk".getBytes();System.out.pri ntln ("fileformat len gth=" + fileformat.le ngth);/*字节流中前4字节为文件长度,4字节文件格式,以后是文件流*/ /*注意如果write里的byte超过socket的缓存,系

48、统自动分包写过 去,所以对方要循环写完*/out.write(filele ngth);out.flush();Stri ng strok1 = readFromSocket(i n);System.out.pri ntl n("service receive filele ngth :" + strok1);/ out.write(fileformat);/ out.flush();/ String strok2 = readFromSocket(i n);/ System.out.pri ntl n("service receive fileformat :&

49、quot; +/ strok2);System.out.pri ntln ("write data to an droid");out.write(filebytes);out.flush();System.out.pri ntln("*");/*服务器反馈:接收成功*/String strread = readFromSocket(i n);System.out.pri ntln (” send data success:" + strread);System.out.printin (”); else if (strWord.equalsI

50、g no reCase("EXIT") out.write("EXIT".getBytes();out.flush();System.out.pri ntln ("EXIT finish sending the data");Stri ng strFormsocket = readFromSocket(i n); System.out.pri ntln ("the data sent by server is:r n" + strFormsocket);flag = false;System.out.pri ntl

51、n("=: ="); catch (UnknownH ostExcepti on e1) System.out.pri ntln ("TCP 331133" + "ERROR:" + e1.toStri ng(); catch (Excepti on e2) System.out.pri ntln( "TCP 441144" + "ERROR:" + e2.toStri ng(); fin ally try if (socket != n ull) socket.close(); System.

52、out.pri ntln ("socket.close()"); catch (IOExceptio n e) System.out.pri ntln( "TCP 5555" + "ERROR:" + e.toStri ng();/*从InputStream流中读数据 */public static String readFromSocket(I nputStream in) int MAX_BUFFER_BYTES = 4000;Stri ng msg =""byte tempbuffer = new byteM

53、AX_BUFFER_BYTES;try int nu mReadedBytes = in. read(tempbuffer, 0, tempbufferen gth); msg = new Strin g(tempbuffer, 0, nu mReadedBytes, "utf-8");tempbuffer = nu II; catch (Excepti on e) e.pri ntStackTrace();/ Log.v(Service139.TAG , "msg=" + msg); return msg;import java.io.Buffered

54、l nputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.i o.I OExcepti on;import java.i o.ln putStream;import java.i o.ln putStreamReader;import java .n et.I netAddress;import java .n et.Socket;import java. net.U nknownH ostExce

55、ptio n;public class testPcClie nt /* param args* throws In terruptedExcepti on*/public static void main( Stri ng args) throws In terruptedExceptio n try Run time.getR un time().exec("adb shell am broadcast -a NotifyServiceStop");Thread.sleep(3000);Run time.getRu ntime().exec("adb forw

56、ard tcp:12580 tcp:10086"); Thread.sleep(3000);Run time.getR un time().exec("adb shell am broadcast -a NotifyServiceStart"); Thread.sleep(3000); catch (IOException e3) e3.pri ntStackTrace();Socket socket = n ull;try In etAddress serverAddr = n ull;serverAddr = In etAddress.getByName(&q

57、uot;127.0.0.1");System.out.pri ntl n( "TCP 1111" + "C: Co nn ecti ng.");socket = new Socket(serverAddr, 12580);String str = "hi,wufe nglon g"System.out.pri ntl n( "TCP 221122" + "C:RECEIVE");BufferedOutputStream out = new BufferedOutputStream(so

58、cket .getOutputStream();Bufferedl nputStream in = new BufferedI nputStream(socket.getI nputStream();BufferedReader br = new BufferedReader( new In putStreamReader( System.i n);boolea n flag = true;while (flag) System.out.print(”请输入16的数字,退出输入exit:");Stri ng strWord = br.readL in e(); 从控制台输入 16if

59、 (strWord.equals("1") out.write("1".getBytes();out.flush();System.out.pri ntln ("1 finish sending the data");Stri ng strFormsocket = readFromSocket(i n);System.out.pri ntln ("the data sent by server is:r n"+ strFormsocket);System.out.println( "="); else if (strWord.equals("2") out.write("2".getBytes();out.flush();System.out.pri ntln ("2 finish sending the data");Stri ng strFormsocket = readFromSocket(i n);System.out.pri ntln ("the

温馨提示

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

评论

0/150

提交评论