PC客戶端與Android服務(wù)端的Socket同步通信_(tái)百度文庫_第1頁
PC客戶端與Android服務(wù)端的Socket同步通信_(tái)百度文庫_第2頁
PC客戶端與Android服務(wù)端的Socket同步通信_(tái)百度文庫_第3頁
PC客戶端與Android服務(wù)端的Socket同步通信_(tái)百度文庫_第4頁
PC客戶端與Android服務(wù)端的Socket同步通信_(tái)百度文庫_第5頁
已閱讀5頁,還剩52頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、PC客戶端與Android服務(wù)端的Socket同步通信(USB) 收藏 需求:1.一個(gè)android端的service后臺(tái)運(yùn)行的程序,作為socket的服務(wù)器端;用于接收Pc client端發(fā)來的命令,來處理數(shù)據(jù)后,把結(jié)果發(fā)給PC client2.PC端程序,作為socket的客戶端,用于給android手機(jī)端發(fā)操作命令難點(diǎn)分析:1.手機(jī)一定要有adb模式,即插上USB線時(shí)馬上提示的對(duì)話框選adb。好多對(duì)手機(jī)的操作都可以用adb直接作。不過,我發(fā)現(xiàn)LG GW880就沒有,要去下載個(gè)3.要想聯(lián)通PC與android手機(jī)的sokcet,一定要用adb forward 來作下端口轉(zhuǎn)發(fā)才能連上sock

2、et.view plaincopy to clipboardprint?Runtime.getRuntime(.exec(adb forward tcp:12580 tcp:10086; Thread.sleep(3000; Runtime.getRuntime(.exec(adb forward tcp:12580 tcp:10086;Thread.sleep(3000; 4.android端的service程序Install到手機(jī)上容易,但是還要有方法來從PC的client端來啟動(dòng)手機(jī)上的service ,這個(gè)辦法可以通過PC端adb命令來發(fā)一個(gè)Broastcast ,手機(jī)端再寫個(gè)接收Br

3、oastcastReceive來接收這個(gè)Broastcast,在這個(gè)BroastcastReceive來啟動(dòng)servicepc端命令:view plaincopy to clipboardprint?Runtime.getRuntime(.exec( adb shell am broadcast -a NotifyServiceStart; Runtime.getRuntime(.exec(adb shell am broadcast -a NotifyServiceStart; android端的代碼:ServiceBroadcastReceiver.javaview plaincopy t

4、o clipboardprint?public class ServiceBroadcastReceiver extends BroadcastReceiver private static String START_ACTION = NotifyServiceStart; private static String STOP_ACTION = NotifyServiceStop; Override public void onReceive(Context context, Intent intent Log.d(androidService.TAG, Thread.currentThrea

5、d(.getName( + - + ServiceBroadcastReceiver onReceive; String action = intent.getAction(; if (START_ACTION.equalsIgnoreCase(action context.startService(new Intent(context, androidService.class; Log.d(androidService.TAG, Thread.currentThread(.getName( + - + ServiceBroadcastReceiver onReceive start end

6、; else if (STOP_ACTION.equalsIgnoreCase(action context.stopService(new Intent(context, androidService.class; Log.d(androidService.TAG, Thread.currentThread(.getName( + - + ServiceBroadcastReceiver onReceive stop end; public class ServiceBroadcastReceiver extends BroadcastReceiver private static Stri

7、ng START_ACTION = NotifyServiceStart;private static String STOP_ACTION = NotifyServiceStop;Overridepublic void onReceive(Context context, Intent intent Log.d(androidService.TAG, Thread.currentThread(.getName( + -+ ServiceBroadcastReceiver onReceive;String action = intent.getAction(;if (START_ACTION.

8、equalsIgnoreCase(action context.startService(new Intent(context, androidService.class;Log.d(androidService.TAG, Thread.currentThread(.getName( + -+ ServiceBroadcastReceiver onReceive start end; else if (STOP_ACTION.equalsIgnoreCase(action context.stopService(new Intent(context, androidService.class;

9、Log.d(androidService.TAG, Thread.currentThread(.getName( + -+ ServiceBroadcastReceiver onReceive stop end;5.由于是USB連接,所以socket就可以設(shè)計(jì)為一但連接就一直聯(lián)通,即在new socket和開完out,in流后,就用個(gè)while(true來循環(huán)PC端和android端的讀和寫android的代碼:view plaincopy to clipboardprint?public void run( Log.d(androidService.TAG, Thread.currentTh

10、read(.getName( + - + a client has connected to server!; BufferedOutputStream out; BufferedInputStream in; try /* PC端發(fā)來的數(shù)據(jù)msg */ String currCMD = ; out = new BufferedOutputStream(client.getOutputStream(; in = new BufferedInputStream(client.getInputStream(; / testSocket(;/ 測(cè)試socket方法 androidService.io

11、ThreadFlag = true; while (androidService.ioThreadFlag try if (!client.isConnected( break; /* 接收PC發(fā)來的數(shù)據(jù) */ Log.v(androidService.TAG, Thread.currentThread(.getName( + - + will read.; /* 讀操作命令 */ currCMD = readCMDFromSocket(in; Log.v(androidService.TAG, Thread.currentThread(.getName( + - + *currCMD = +

12、 currCMD; /* 根據(jù)命令分別處理數(shù)據(jù) */ 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(OK.getBytes(; out.flush(; else if (currCMD.equals(4 /* 準(zhǔn)備接收文件數(shù)據(jù) */ try out.write(service receive OK.getBytes(; out.flu

13、sh(; catch (IOException e e.printStackTrace(; /* 接收文件數(shù)據(jù),4字節(jié)文件長度,4字節(jié)文件格式,其后是文件數(shù)據(jù) */ byte filelength = new byte4; byte fileformat = new byte4; byte filebytes = null; /* 從socket流中讀取完整文件數(shù)據(jù) */ filebytes = receiveFileFromSocket(in, out, filelength, fileformat; / Log.v(Service139.TAG, receive data = + new

14、/ String(filebytes; try /* 生成文件 */ File file = FileHelper.newFile(R0013340.JPG; FileHelper.writeFile(file, filebytes, 0, filebytes.length; catch (IOException e e.printStackTrace(; else if (currCMD.equals(exit catch (Exception e / try / out.write(error.getBytes(utf-8; / out.flush(; / catch (IOExcepti

15、on e1 / e1.printStackTrace(; / Log.e(androidService.TAG, Thread.currentThread(.getName( + - + read write error111111; out.close(; in.close(; catch (Exception e Log.e(androidService.TAG, Thread.currentThread(.getName( + - + read write error222222; e.printStackTrace(; finally try if (client != null Lo

16、g.v(androidService.TAG, Thread.currentThread(.getName( + - + client.close(; client.close(; catch (IOException e Log.e(androidService.TAG, Thread.currentThread(.getName( + - + read write error333333; e.printStackTrace(; public void run( Log.d(androidService.TAG, Thread.currentThread(.getName( + -+ a

17、client has connected to server!;BufferedOutputStream out;BufferedInputStream in;try /* PC端發(fā)來的數(shù)據(jù)msg */String currCMD = ;out = new BufferedOutputStream(client.getOutputStream(;in = new BufferedInputStream(client.getInputStream(;/ testSocket(;/ 測(cè)試socket方法androidService.ioThreadFlag = true;while (androi

18、dService.ioThreadFlag try if (!client.isConnected( break;/* 接收PC發(fā)來的數(shù)據(jù) */Log.v(androidService.TAG, Thread.currentThread(.getName(+ - + will read.;/* 讀操作命令 */currCMD = readCMDFromSocket(in;Log.v(androidService.TAG, Thread.currentThread(.getName(+ - + *currCMD = + currCMD;/* 根據(jù)命令分別處理數(shù)據(jù) */if (currCMD.eq

19、uals(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 /* 準(zhǔn)備接收文件數(shù)據(jù) */try out.write(service receive OK.getBytes(;out.flush(; catch (IOException e e.printStackTrace(;/

20、* 接收文件數(shù)據(jù),4字節(jié)文件長度,4字節(jié)文件格式,其后是文件數(shù)據(jù) */byte filelength = new byte4;byte fileformat = new byte4;byte filebytes = null;/* 從socket流中讀取完整文件數(shù)據(jù) */filebytes = receiveFileFromSocket(in, out, filelength,fileformat;/ Log.v(Service139.TAG, receive data = + new/ String(filebytes;try /* 生成文件 */File file = FileHelper

21、.newFile(R0013340.JPG;FileHelper.writeFile(file, filebytes, 0,filebytes.length; catch (IOException e e.printStackTrace(; else if (currCMD.equals(exit catch (Exception e / try / out.write(error.getBytes(utf-8;/ out.flush(;/ catch (IOException e1 / e1.printStackTrace(;/ Log.e(androidService.TAG, Threa

22、d.currentThread(.getName(+ - + read write error111111;out.close(;in.close(; catch (Exception e Log.e(androidService.TAG, Thread.currentThread(.getName(+ - + read write error222222;e.printStackTrace(; finally try if (client != null Log.v(androidService.TAG, Thread.currentThread(.getName(+ - + client.

23、close(;client.close(; catch (IOException e Log.e(androidService.TAG, Thread.currentThread(.getName(+ - + read write error333333;e.printStackTrace(; 6.如果是在PC端和android端的讀寫操作來while(true循環(huán),這樣socket流的結(jié)尾不好判斷,不能用“-1”來判斷,因?yàn)椤?1”是只有在socket關(guān)閉時(shí)才作為判斷結(jié)尾。android端接收數(shù)據(jù)的代碼:view plaincopy to clipboardprint?/* * 功能:從so

24、cket流中讀取完整文件數(shù)據(jù) * * InputStream in:socket輸入流 * * byte filelength: 流的前4個(gè)字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的字節(jié)數(shù) * * byte fileformat:流的前5-8字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的格式(如.apk) * * */ public static byte receiveFileFromSocket(InputStream in, OutputStream out, byte filelength, byte fileformat byte filebytes = null;/ 文件數(shù)據(jù) try int filelen = MyUtil

25、.bytesToInt(filelength;/ 文件長度從4字節(jié)byte轉(zhuǎn)成Int String strtmp = read file length ok: + filelen; out.write(strtmp.getBytes(utf-8; out.flush(; filebytes = new bytefilelen; int pos = 0; int rcvLen = 0; while (rcvLen = in.read(filebytes, pos, filelen - pos 0 pos += rcvLen; Log.v(androidService.TAG, Thread.cu

26、rrentThread(.getName( + - + read file OK:file size= + filebytes.length; out.write(read file ok.getBytes(utf-8; out.flush(; catch (Exception e Log.v(androidService.TAG, Thread.currentThread(.getName( + - + receiveFileFromSocket error; e.printStackTrace(; return filebytes; /* 功能:從socket流中讀取完整文件數(shù)據(jù)* * I

27、nputStream in:socket輸入流* * byte filelength: 流的前4個(gè)字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的字節(jié)數(shù)* * byte fileformat:流的前5-8字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的格式(如.apk)* * */public static byte receiveFileFromSocket(InputStream in,OutputStream out, byte filelength, byte fileformat byte filebytes = null;/ 文件數(shù)據(jù)try int filelen = MyUtil.bytesToInt(filelength;/ 文

28、件長度從4字節(jié)byte轉(zhuǎn)成IntString strtmp = read file length ok: + filelen;out.write(strtmp.getBytes(utf-8;out.flush(;filebytes = new bytefilelen;int pos = 0;int rcvLen = 0;while (rcvLen = in.read(filebytes, pos, filelen - pos 0 pos += rcvLen;Log.v(androidService.TAG, Thread.currentThread(.getName(+ - + read fi

29、le OK:file size= + filebytes.length;out.write(read file ok.getBytes(utf-8;out.flush(; catch (Exception e Log.v(androidService.TAG, Thread.currentThread(.getName(+ - + receiveFileFromSocket error;e.printStackTrace(;return filebytes; 8.socket的最重要的機(jī)制就是讀寫采用的是阻塞的方式,如果客戶端作為命令發(fā)起者,服務(wù)器端作為接收者的話,只有當(dāng)客戶端client用o

30、ut.writer(寫到輸出流里后,即流中有數(shù)據(jù)service的read才會(huì)執(zhí)行,不然就會(huì)一直停在read(那里等數(shù)據(jù)。9.還要讓服務(wù)器端可以同時(shí)連接多個(gè)client,即服務(wù)器端用new thread(來作數(shù)據(jù)讀取操作。源碼:客戶端(pc端):testPcClient.javaview plaincopy to clipboardprint?public class testPcClient /* * param args * throws InterruptedException */ public static void main(String args throws Interrupte

31、dException try Runtime.getRuntime(.exec( adb shell am broadcast -a NotifyServiceStop; Thread.sleep(3000; Runtime.getRuntime(.exec(adb forward tcp:12580 tcp:10086; Thread.sleep(3000; Runtime.getRuntime(.exec( adb shell am broadcast -a NotifyServiceStart; Thread.sleep(3000; catch (IOException e3 e3.pr

32、intStackTrace(; Socket socket = null; try InetAddress serverAddr = null; socket = new Socket(serverAddr, 12580; String str = hi,wufenglong; BufferedOutputStream out = new BufferedOutputStream(socket .getOutputStream(; BufferedInputStream in = new BufferedInputStream(socket .getInputStream(; Buffered

33、Reader br = new BufferedReader(new InputStreamReader( System.in; boolean flag = true; while (flag String strWord = br.readLine(;/ 從控制臺(tái)輸入16 if (strWord.equals(1 out.write(1.getBytes(; out.flush(; String strFormsocket = readFromSocket(in; + strFormsocket; System.out .println(=; else if (strWord.equals

34、(2 out.write(2.getBytes(; out.flush(; String strFormsocket = readFromSocket(in; + strFormsocket; System.out .println(=; else if (strWord.equals(3 out.write(3.getBytes(; out.flush(; String strFormsocket = readFromSocket(in; + strFormsocket; System.out .println(=; else if (strWord.equals(4 /* 發(fā)送命令 */

35、out.write(4.getBytes(; out.flush(; /* 服務(wù)器反饋:準(zhǔn)備接收 */ String strFormsocket = readFromSocket(in; System.out .println(service ready receice data:UPDATE_CONTACTS: + strFormsocket; byte filebytes = FileHelper.readFile(R0013340.JPG; /* 將整數(shù)轉(zhuǎn)成4字節(jié)byte數(shù)組 */ byte filelength = new byte4; filelength = To

36、Byte(filebytes.length; /* 將.apk字符串轉(zhuǎn)成4字節(jié)byte數(shù)組 */ byte fileformat = null; fileformat = .apk.getBytes(; System.out .println(fileformat length= + fileformat.length; /* 字節(jié)流中前4字節(jié)為文件長度,4字節(jié)文件格式,以后是文件流 */ /* 注意如果write里的byte超過socket的緩存,系統(tǒng)自動(dòng)分包寫過去,所以對(duì)方要循環(huán)寫完 */ out.write(filelength; out.flush(; String strok1 =

37、readFromSocket(in; / out.write(fileformat; / out.flush(; / String strok2 = readFromSocket(in; / strok2; out.write(filebytes; out.flush(; /* 服務(wù)器反饋:接收成功 */ String strread = readFromSocket(in; System.out .println(=; else if (strWord.equalsIgnoreCase(EXIT out.write(EXIT.getBytes(; out.flush(; String str

38、Formsocket = readFromSocket(in; + strFormsocket; flag = false; System.out .println(=; catch (UnknownHostException e1 catch (Exception e2 finally try if (socket != null socket.close(; catch (IOException e /* 從InputStream流中讀數(shù)據(jù) */ public static String readFromSocket(InputStream in int MAX_BUFFER_BYTES

39、= 4000; String msg = ; byte tempbuffer = new byteMAX_BUFFER_BYTES; try int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length; msg = new String(tempbuffer, 0, numReadedBytes, utf-8; tempbuffer = null; catch (Exception e e.printStackTrace(; / Log.v(Service139.TAG, msg= + msg; return msg; publi

40、c class testPcClient /* param args* throws InterruptedException*/public static void main(String args throws InterruptedException try Runtime.getRuntime(.exec(adb shell am broadcast -a NotifyServiceStop;Thread.sleep(3000;Runtime.getRuntime(.exec(adb forward tcp:12580 tcp:10086;Thread.sleep(3000;Runti

41、me.getRuntime(.exec(adb shell am broadcast -a NotifyServiceStart;Thread.sleep(3000; catch (IOException e3 e3.printStackTrace(;Socket socket = null;try InetAddress serverAddr = null;socket = new Socket(serverAddr, 12580;String str = hi,wufenglong;BufferedOutputStream out = new BufferedOutputStream(so

42、cket.getOutputStream(;BufferedInputStream in = new BufferedInputStream(socket.getInputStream(;BufferedReader br = new BufferedReader(new InputStreamReader(System.in;boolean flag = true;while (flag String strWord = br.readLine(;/ 從控制臺(tái)輸入16if (strWord.equals(1 out.write(1.getBytes(;out.flush(;String st

43、rFormsocket = readFromSocket(in;+ strFormsocket;System.out.println(=; else if (strWord.equals(2 out.write(2.getBytes(;out.flush(;String strFormsocket = readFromSocket(in;+ strFormsocket;System.out.println(=; else if (strWord.equals(3 out.write(3.getBytes(;out.flush(;String strFormsocket = readFromSo

44、cket(in;+ strFormsocket;System.out.println(=; else if (strWord.equals(4 /* 發(fā)送命令 */out.write(4.getBytes(;out.flush(;/* 服務(wù)器反饋:準(zhǔn)備接收 */String strFormsocket = readFromSocket(in;System.out.println(service ready receice data:UPDATE_CONTACTS:+ strFormsocket;byte filebytes = FileHelper.readFile(R0013340.JPG;

45、/* 將整數(shù)轉(zhuǎn)成4字節(jié)byte數(shù)組 */byte filelength = new byte4;filelength = ToByte(filebytes.length;/* 將.apk字符串轉(zhuǎn)成4字節(jié)byte數(shù)組 */byte fileformat = null;fileformat = .apk.getBytes(;System.out.println(fileformat length= + fileformat.length;/* 字節(jié)流中前4字節(jié)為文件長度,4字節(jié)文件格式,以后是文件流 */* 注意如果write里的byte超過socket的緩存,系統(tǒng)自動(dòng)分包寫過去

46、,所以對(duì)方要循環(huán)寫完 */out.write(filelength;out.flush(;String strok1 = readFromSocket(in;/ out.write(fileformat;/ out.flush(;/ String strok2 = readFromSocket(in;/ strok2;out.write(filebytes;out.flush(;/* 服務(wù)器反饋:接收成功 */String strread = readFromSocket(in;System.out.println(=; else if (strWord.equalsIgnoreCase(EX

47、IT out.write(EXIT.getBytes(;out.flush(;String strFormsocket = readFromSocket(in;+ strFormsocket;flag = false;System.out.println(=; catch (UnknownHostException e1 catch (Exception e2 finally try if (socket != null socket.close(; catch (IOException e /* 從InputStream流中讀數(shù)據(jù) */public static String readFro

48、mSocket(InputStream in int MAX_BUFFER_BYTES = 4000;String msg = ;byte tempbuffer = new byteMAX_BUFFER_BYTES;try int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length;msg = new String(tempbuffer, 0, numReadedBytes, utf-8;tempbuffer = null; catch (Exception e e.printStackTrace(;/ Log.v(Service

49、139.TAG, msg= + msg;return msg;android服務(wù)器端:主類androidService.javaview plaincopy to clipboardprint?/* * 設(shè)置:android手機(jī) * * * */ public class androidService extends Service public static final String TAG = TAG; public static Boolean mainThreadFlag = true; public static Boolean ioThreadFlag = true; Server

50、Socket serverSocket = null; final int SERVER_PORT = 10086; File testFile; private sysBroadcastReceiver sysBR; Override public void onCreate( super.onCreate(; Log.v(TAG, Thread.currentThread(.getName( + - + onCreate; /* 創(chuàng)建內(nèi)部類sysBroadcastReceiver 并注冊(cè)registerReceiver */ sysRegisterReceiver(; new Thread( public void run( doListen(; ; .start(; private void doListen( Log.d(TAG, Thread.currentThread(.getName( + - + doListen( START; serverSocket = null; try Log.d(TAG, Thread.currentThread(.getName( + - + doListen( new serverSocket; serverSocket = n

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論