版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、PC 客戶端與 Android 服務(wù)端的 Socket 同步通信(USB)收藏需求:1 .一個(gè) android 端的 service 后臺(tái)運(yùn)行的程序,作為 socket 的服務(wù)器端;用于接收 Pcclient 端發(fā)來(lái)的命令,來(lái)處理數(shù)據(jù)后,把結(jié)果發(fā)給 PCclient2.PC 端程序, 作為 socket 的客戶端, 用于給 android 手機(jī)端發(fā)操作命令難點(diǎn)分析:1 .手機(jī)一定要有 adb 模式,即插上 USB 線時(shí)馬上提示白對(duì)話框選adb。好多對(duì)手機(jī)的操作都可以用 adb 直接作。不過(guò),我發(fā)現(xiàn) LGGW880 就沒(méi)有,要去下載個(gè)2 .android 默認(rèn)手機(jī)端的 IP 為“127.0.0.
2、1”3 .要想聯(lián)通 PC 與 android 手機(jī)的 sokcet,一定要用 adbforward 來(lái)作下端口轉(zhuǎn)發(fā)才能連上 socket.viewplaincopytoclipboardprint?Runtime.getRuntime().exec(adbforwardtcp:12580tcp:10086);Thread.sleep(3000);Runtime.getRuntime().exec(adbforwardtcp:12580tcp:10086);Thread.sleep(3000);4 .android 端的 service 程序 Install 到手機(jī)上容易,但是還要有方法來(lái)從 P
3、C 的 client端來(lái)啟動(dòng)手機(jī)上的 service,這個(gè)辦法可以通過(guò) PC 端 adb 命令來(lái)發(fā)一個(gè)Broastcast,手機(jī)端再寫個(gè)接收 BroastcastReceive 來(lái)接收這個(gè) Broastcast,在這個(gè) BroastcastReceive 來(lái)啟動(dòng) servicepc 端命令:viewplaincopytoclipboardprint?Runtime.getRuntime().exec(adbshellambroadcast-aNotifyServiceStart);Runtime.getRuntime().exec(adbshellambroadcast-aNotifyServ
4、iceStart);android 端的代碼:ServiceBroadcastReceiver.javaviewplaincopytoclipboardprint?packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiverprivatestat
5、icStringSTART_ACTION=NotifyServiceStart;privatestaticStringSTOP_ACTION=NotifyServiceStop;OverridepublicvoidonReceive(Contextcontext,Intentintent)Log.d(androidService.TAG,Thread.currentThread().getName()+ServiceBroadcastReceiveronReceive);Stringaction=intent.getAction();if(START_ACTION.equalsIgnoreCa
6、se(action)context.startService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+ServiceBroadcastReceiveronReceivestartend);elseif(STOP_ACTION.equalsIgnoreCase(action)context.stopService(newIntent(context,androidService.class);Log.d(androidService.TAG,
7、Thread.currentThread().getName()+ServiceBroadcastReceiveronReceivestopend);packagecom.otheri.service;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiverprivatestaticStrin
8、gSTART_ACTION=NotifyServiceStart;privatestaticStringSTOP_ACTION=NotifyServiceStop;OverridepublicvoidonReceive(Contextcontext,Intentintent)Log.d(androidService.TAG,Thread.currentThread().getName()+ServiceBroadcastReceiveronReceive);Stringaction=intent.getAction();if(START_ACTION.equalsIgnoreCase(acti
9、on)context.startService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.currentThread().getName()+ServiceBroadcastReceiveronReceivestartend);elseif(STOP_ACTION.equalsIgnoreCase(action)context.stopService(newIntent(context,androidService.class);Log.d(androidService.TAG,Thread.
10、currentThread().getName()+ServiceBroadcastReceiveronReceivestopend);5.由于是 USB 連接,所以 socket 就可以設(shè)計(jì)為一但連接就一直聯(lián)通,即在newsocket和開(kāi)完out,in流后, 就用個(gè)while(true)來(lái)循環(huán)PC端和android端的讀和寫android 的代碼:viewplaincopytoclipboardprint?publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+aclienthasconnectedto
11、server!);BufferedOutputStreamout;BufferedInputStreamin;try/*PC 端發(fā)來(lái)的數(shù)據(jù) msg*/StringcurrCMD=;out=newBufferedOutputStream(client.getOutputStream();in=newBufferedInputStream(client.getInputStream();testSocket();/測(cè)試 socket 方法androidService.ioThreadFlag=true;while(androidService.ioThreadFlag)tryif(!client.
12、isConnected()break;/*接收 PC 發(fā)來(lái)的數(shù)據(jù)*/Log.v(androidService.TAG,Thread.currentThread().getName()+一+willread.);/*讀操作命令*/currCMD=readCMDFromSocket(in);Log.v(androidService.TAG,Thread.currentThread().getName()+-+*currCMD=+currCMD);/*根據(jù)命令分別處理數(shù)據(jù)*/if(currCMD.equals(1)out.write(OK.getBytes();out.flush();elseif(
13、currCMD.equals(2)out.write(OK.getBytes();out.flush();elseif(currCMD.equals(3)out.write(OK.getBytes();out.flush();elseif(currCMD.equals(4)/*準(zhǔn)備接收文件數(shù)據(jù)*/tryout.write(servicereceiveOK.getBytes();out.flush();catch(IOExceptione)e.printStackTrace();/*接收文件數(shù)據(jù),4 字節(jié)文件長(zhǎng)度,4 字節(jié)文件格式,其后是文件數(shù)據(jù)*/byte 口filelength=newbyt
14、e4;bytefileformat=newbyte4;bytefilebytes=null;/*從 socket 流中讀取完整文件數(shù)據(jù)*/filebytes=receiveFileFromSocket(in,out,filelength,fileformat);/Log.v(Service139.TAG,receivedata=+new/String(filebytes);try/*生成文件*/Filefile=FileHelper.newFile(R0013340.JPG);FileHelper.writeFile(file,filebytes,0,filebytes.length);cat
15、ch(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()+-+readwriteerror111111);out.close();in.close();catch(Exceptione)Log
16、.e(androidService.TAG,Thread.currentThread().getName()+-+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()+-+readwr
17、iteerror333333);e.printStackTrace();publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+aclienthasconnectedtoserver!);BufferedOutputStreamout;BufferedInputStreamin;try/*PC 端發(fā)來(lái)的數(shù)據(jù) msg*/StringcurrCMD=;out=newBufferedOutputStream(client.getOutputStream();in=newBufferedInputStream(c
18、lient.getInputStream();/testSocket();/測(cè)試 socket 方法androidService.ioThreadFlag=true;while(androidService.ioThreadFlag)tryif(!client.isConnected()break;/*接收 PC 發(fā)來(lái)的數(shù)據(jù)*/Log.v(androidService.TAG,Thread.currentThread().getName()+一+willread.);/*讀操作命令*/currCMD=readCMDFromSocket(in);Log.v(androidService.TAG,
19、Thread.currentThread().getName()+-+*currCMD=+currCMD);/*根據(jù)命令分別處理數(shù)據(jù)*/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)/*準(zhǔn)備接收文件數(shù)據(jù)*/tryout.write(service
20、receiveOK.getBytes();out.flush();catch(IOExceptione)e.printStackTrace();/*接收文件數(shù)據(jù),4 字節(jié)文件長(zhǎng)度,4 字節(jié)文件格式,其后是文件數(shù)據(jù)*/byte 口 filelength=newbyte4;bytefileformat=newbyte4;bytefilebytes=null;/*從 socket 流中讀取完整文件數(shù)據(jù)*/filebytes=receiveFileFromSocket(in,out,filelength,fileformat);/Log.v(Service139.TAG,receivedata=+ne
21、w/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.getBytes(utf-8);/out.flush();/catch(IOExceptione1)/e1.printStackTra
22、ce();/Log.e(androidService.TAG,Thread.currentThread().getName()+-+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.currentThrea
23、d().getName()+-+client.close();client.close();catch(IOExceptione)Log.e(androidService.TAG,Thread.currentThread().getName()+-+readwriteerror333333);e.printStackTrace();6.如果是在 PC 端和 android 端的讀寫操作來(lái) while(true)循環(huán),這樣socket 流的結(jié)尾不好判斷,不能用-1”來(lái)判斷,因?yàn)?1”是只有在 socket 關(guān)閉時(shí)才作為判斷結(jié)尾。7.socket 在 out.write(bytes);時(shí),要是數(shù)據(jù)
24、太大時(shí),超過(guò) socket 的緩存,socket 自動(dòng)分包發(fā)送,所以對(duì)方就一定要用循環(huán)來(lái)多次讀。最好的辦法就是服務(wù)器和客戶端協(xié)議好,比如發(fā)文件時(shí),先寫過(guò)來(lái)一個(gè)要發(fā)送的文件的大小,然后再發(fā)送文件;對(duì)方用這個(gè)大小,來(lái)循環(huán)讀取數(shù)據(jù)。android 端接收數(shù)據(jù)的代碼:viewplaincopytoclipboardprint?/* 功能:從 socket 流中讀取完整文件數(shù)據(jù)* InputStreamin:socket 輸入流* bytefilelength:流的前 4 個(gè)字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的字節(jié)數(shù)* bytefileformat:流的前 5-8 字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的格式(如* */publics
25、taticbytereceiveFileFromSocket(InputStreamin,OutputStreamout,bytefilelength,bytefileformat)bytefilebytes=null;/文件數(shù)據(jù)tryintfilelen=MyUtil.bytesToInt(filelength);/文件長(zhǎng)度從 4 字節(jié)byte 口轉(zhuǎn)成 IntStringstrtmp=readfilelengthok:+filelen;out.write(strtmp.getBytes(utf-8);out.flush();filebytes=newbytefilelen;intpos=0;
26、intrcvLen=0;while(rcvLen=in.read(filebytes,pos,filelen-pos)0)pos+=rcvLen;Log.v(androidService.TAG,Thread.currentThread().getName()+-+readfileOK:filesize=+filebytes.length);out.write(readfileok.getBytes(utf-8);out.flush();catch(Exceptione)Log.v(androidService.TAG,Thread.currentThread().getName()+-+re
27、ceiveFileFromSocketerror);.apk)e.printStackTrace();)returnfilebytes;* InputStreamin:socket 輸入流* bytefilelength:流的前 4 個(gè)字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的字節(jié)數(shù)* bytefileformat:流的前 5-8 字節(jié)存儲(chǔ)要轉(zhuǎn)送的文件的格式(如.apk)*/publicstaticbytereceiveFileFromSocket(InputStreamin,OutputStreamout,bytefilelength,bytefileformat)bytefilebytes=null;/文件數(shù)
28、據(jù)tryintfilelen=MyUtil.bytesTolnt(filelength);/文件長(zhǎng)度從 4 字節(jié)byte 口轉(zhuǎn)成 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.currentT
29、hread().getName()+-+readfileOK:filesize=+filebytes.leng/*功能:從 socket 流中讀取完整文件數(shù)據(jù)th);out.write(readfileok.getBytes(utf-8);out.flush();catch(Exceptione)Log.v(androidService.TAG,Thread.currentThread().getName()+-+receiveFileFromSocketerror);e.printStackTrace();returnfilebytes;8.socket 的最重要的機(jī)制就是讀寫采用的是阻塞的
30、方式,如果客戶端作為命令發(fā)起者,服務(wù)器端作為接收者的話,只有當(dāng)客戶端 client 用 out.writer()寫到輸出流里后,即流中有數(shù)據(jù) service 的 read 才會(huì)執(zhí)行,不然就會(huì)一直停在 read()那里等數(shù)據(jù)。9.還要讓服務(wù)器端可以同時(shí)連接多個(gè)client,即服務(wù)器端用newthread()來(lái)作數(shù)據(jù)讀取操作。源碼:客戶端(pc 端):testPcClient.javaviewplaincopytoclipboardprint?importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjav
31、a.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.InetAddress;.Socket;.UnknownHostException;publicclasstestPcClient/*paramargsthrowsInterruptedException*/publicstaticvoidmain(String 口args)throwsInterruptedExce
32、ptiontryRuntime.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)e3.printStackTrace();Socke
33、tsocket=null;try(InetAddressserverAddr=null;serverAddr=InetAddress.getByName();System.out.println(TCP1111+C:Connecting.);socket=newSocket(serverAddr,12580);Stringstr=hi,wufenglong;System.out.println(TCP221122+C:RECEIVE);BufferedOutputStreamout=newBufferedOutputStream(socket.getOutputStream(
34、);BufferedInputStreamin=newBufferedInputStream(socket.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in);booleanflag=true;while(flag)System.out.print(請(qǐng)輸入 16 的數(shù)字, 退出輸入exit:);StringstrWord=br.readLine();從控制臺(tái)輸入 16if(strWord.equals(1)out.write(1.getBytes();out.flush();Sy
35、stem.out.println(1finishsendingthedata);StringstrFormsocket=readFromSocket(in);System.out.println(thedatasentbyserveris:rn+strFormsocket);System.out.println(=);elseif(strWord.equals(2)out.write(2.getBytes();out.flush();System.out.println(2finishsendingthedata);StringstrFormsocket=readFromSocket(in);
36、System.out.println(thedatasentbyserveris:rn+strFormsocket);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.println(=
37、);elseif(strWord.equals(4)/*發(fā)送命令*/out.write(4.getBytes();out.flush();System.out.println(sendfilefinishsendingtheCMD:);/*服務(wù)器反饋:準(zhǔn)備接收*/StringstrFormsocket=readFromSocket(in);System.out.println(servicereadyreceicedata:UPDATE_CONTACTS:+strFormsocket);bytefilebytes=FileHelper.readFileCR0013340.JPG);System
38、.out.println(filesize=+filebytes.length);/*將整數(shù)轉(zhuǎn)成 4 字節(jié) byte 數(shù)組*/bytefilelength=newbyte4;filelength=ToByte(filebytes.length);/*將.apk 字符串轉(zhuǎn)成 4 字節(jié) byte 數(shù)組*/bytefileformat=null;fileformat=.apk.getBytes();System.out.println(fileformatlength=+fileformat.length);/*字節(jié)流中前 4 字節(jié)為文件長(zhǎng)度, 4 字節(jié)文件格式,以后是文件流/*注
39、意如果 write 里的 byte 口超過(guò) socket 的緩存,*/系統(tǒng)自動(dòng)分包寫過(guò)去,所以對(duì)方要循環(huán)寫完*/out.write(filelength);out.flush();Stringstrok1=readFromSocket(in);System.out.println(servicereceivefilelength:+strok1);/out.write(fileformat);/out.flush();/Stringstrok2=readFromSocket(in);/System.out.println(servicereceivefileformat:+/strok2);S
40、ystem.out.println(writedatatoandroid);out.write(filebytes);out.flush();System.out.println(*);/*服務(wù)器反饋:接收成功*/Stringstrread=readFromSocket(in);System.out.println(senddatasuccess:+strread);System.out.println(=:=);elseif(strWord.equalsIgnoreCase(EXIT)out.write(EXIT.getBytes();out.flush();System.out.print
41、ln(EXITfinishsendingthedata);StringstrFormsocket=readFromSocket(in);System.out.println(thedatasentbyserveris:rn+strFormsocket);flag=false;System.out.println(=:=);catch(UnknownHostExceptione1)System.out.println(TCP331133+ERROR:+e1.toString();catch(Exceptione2)System.out.println(TCP441144+ERROR:+e2.to
42、String();finallytryif(socket!=null)socket.close();System.out.println(socket.close();catch(IOExceptione)System.out.println(TCP5555+ERROR:+e.toString();/*從 InputStream 流中讀數(shù)據(jù)*/publicstaticStringreadFromSocket(InputStreamin)intMAX_BUFFER_BYTES=4000;Stringmsg=;bytetempbuffer=newbyteMAX_BUFFER_BYTES;tryin
43、tnumReadedBytes=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.BufferedReader;i
44、mportjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.InetAddress;.Socket;.UnknownHostException;publicclasstestPcClient/*paramargsthrowsInterruptedException*/publicstaticvoidmain(String 口 args)throwsInterruptedExceptiontryRuntime.getR
45、untime().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)e3.printStackTrace();Socketsocket=null;tryInet
46、AddressserverAddr=null;serverAddr=InetAddress.getByName();System.out.println(TCP1111+C:Connecting.);socket=newSocket(serverAddr,12580);Stringstr=hi,wufenglong;System.out.println(TCP221122+C:RECEIVE);BufferedOutputStreamout=newBufferedOutputStream(socket.getOutputStream();BufferedInputStreamin=newBufferedInputStream(socket.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in);booleanflag=true;while(
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 購(gòu)木材定金合同模板
- 應(yīng)收賬款管理課程設(shè)計(jì)
- 應(yīng)變壓力傳感課程設(shè)計(jì)
- 閱讀課程合同模板
- 職工住宅合同模板
- 汽貿(mào)汽車銷售合同模板
- 廣聯(lián)達(dá)場(chǎng)地布置課程設(shè)計(jì)
- 廣本車?yán)瓧U止墊課程設(shè)計(jì)
- 廣工精密設(shè)計(jì)課程設(shè)計(jì)
- 訂貨檔案合同模板
- 《外科縫合術(shù)》教學(xué)課件
- HIS醫(yī)療軟件管理系統(tǒng)驗(yàn)收?qǐng)?bào)告
- 華東師大版九年級(jí)數(shù)學(xué)上冊(cè)教案全冊(cè)
- 湖南懷化市醫(yī)療保障局基金核查和結(jié)算中心選調(diào)【共500題附答案解析】模擬試卷
- 農(nóng)業(yè)生態(tài)學(xué)全套課件
- 普通高校大學(xué)生信息素養(yǎng)大賽考試題庫(kù)(濃縮500題)
- 湘教湘科版科學(xué)(2017)六年級(jí)上冊(cè)期中測(cè)試卷及答案
- 繪圖員高級(jí)繪圖員崗位月度KPI績(jī)效考核表
- 有關(guān)travel的英語(yǔ)演講課件
- DB32T 4065-2021 建筑幕墻工程技術(shù)標(biāo)準(zhǔn)
- 美容師月度KPI績(jī)效考核表
評(píng)論
0/150
提交評(píng)論