![客戶端與android服務端socket同步通信_第1頁](http://file4.renrendoc.com/view/d5634d969971ff03f78f0d562d610f05/d5634d969971ff03f78f0d562d610f051.gif)
![客戶端與android服務端socket同步通信_第2頁](http://file4.renrendoc.com/view/d5634d969971ff03f78f0d562d610f05/d5634d969971ff03f78f0d562d610f052.gif)
![客戶端與android服務端socket同步通信_第3頁](http://file4.renrendoc.com/view/d5634d969971ff03f78f0d562d610f05/d5634d969971ff03f78f0d562d610f053.gif)
![客戶端與android服務端socket同步通信_第4頁](http://file4.renrendoc.com/view/d5634d969971ff03f78f0d562d610f05/d5634d969971ff03f78f0d562d610f054.gif)
![客戶端與android服務端socket同步通信_第5頁](http://file4.renrendoc.com/view/d5634d969971ff03f78f0d562d610f05/d5634d969971ff03f78f0d562d610f055.gif)
版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
PCAndroidSocket同步通信(USB)一個android端的service運行的程序作為socket的服務器端;用于接收Pc端發(fā)來令,來處理數據后,把結果發(fā)給PCPC端程序,作為socket的客戶端,用于給android端發(fā)操作命令一定要有adb模式,即插上USB線時馬上提示的框選adb。好多對的adb直接作。不過,我發(fā)現LGGW880就沒有,要去android默認端的IP為要想PC與android的sokcet,一定要用adbforward來作下端口轉發(fā)才能連socket.viewplaincopytoclipboardprint?Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");android端的service程序Install到上容易,但是還要有方法來從PC的端來啟動上的service,這個辦法可以通過PC端adb命令來發(fā)一個Broastcast端再寫個接收BroastcastReceive來接收這個Broastcast,在這個BroastcastReceivepcviewplaincopyto"adbsambroadcast-aNotifyServiceStart");"adbsambroadcast-aNotifyServiceStart");viewplaincopytoclipboardprint?packageimportandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiver{privatestaticStringSTART_ACTION="NotifyServiceStart";privatestaticStringSTOP_ACTION="NotifyServiceStop";publicvoidonReceive(Contextcontext,Intentintent){Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiverStringaction=if(START_ACTION.equalsIgnoreCase(action)){context.startService(newIntent(context,androidService.class)); +"ServiceBroadcastReceiveronReceivestart}elseif(STOP_ACTION.equalsIgnoreCase(action)){context.stopService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiveronReceivestop}}}packageimportandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiver{privatestaticStringSTART_ACTION="NotifyServiceStart";privatestaticStringSTOP_ACTION="NotifyServiceStop";publicvoidonReceive(Contextcontext,Intentintent){Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiverStringaction=if(START_ACTION.equalsIgnoreCase(action)){context.startService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+ +"ServiceBroadcastReceiveronReceivestart}elseif(STOP_ACTION.equalsIgnoreCase(action)){context.stopService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiveronReceivestop}}}由于是USB連接,所以socket就可以設計為一但連接就一直,即在newsocket和out,inwhile(true){}PCandroid端的讀和寫androidviewplaincopytoclipboardprint?publicvoidrun(){Log.d(androidService.TAG,Thread.currentThread().getName()+ +"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PCmsg*/StringcurrCMD="";out=newBufferedOutputStream(client.getOutputStream());in=newBufferedInputStream(client.getInputStream());//testSocket();//socket方法androidService.ioThreadFlag=true;whileandroidService.ioThreadFlag)tryif(!client.isConnected()){}/*PC發(fā)來的數據+"---->"+"will /*currCMD=readCMDFromSocket(in);+ >"+"**currCMD===="+/**/if(currCMD.equals("1")){}elseif(currCMD.equals("2"))}elseif(currCMD.equals("3"))}elseif(currCMD.equals("4"))/**/try{out.write("servicereceiveOK".getBytes());}catch(IOExceptione){}件數據
/*接收文件數據,4字節(jié)文件長度,4byte[]filelength=newbyte[4];byte[]fileformat=newbyte[4];byte[]filebytes=null;/*從socket流中完整文件數據filebytes=receiveFileFromSocket(in,out,filelength,//Log.v(Service139.TAG,"receivedata="+//String(filebytes));try{/*Filefile=FileHelper.newFile("R0013340.JPG");FileHelper.writeFile(file,filebytes,0,}catch(IOExceptione){}}elseif(currCMD.equals("exit"))}}catch(Exceptione)//try//out.write("error".getBytes("utf-////}catch(IOExceptione1)////+ >"+"readwrite}}}catch(Exceptione)+ >"+"readwrite}finallytryif(client!=null)+ >"+}}catch(IOExceptione)+ >"+"readwrite}}publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+ +"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PCmsg*/StringcurrCMD="";out=newBufferedOutputStream(client.getOutputStream());in=newBufferedInputStream(client.getInputStream());//testSocket();//socket方法androidService.ioThreadFlag=true;whileandroidService.ioThreadFlag)tryif(!client.isConnected()){}/*PC+"---->"+"will /*讀操作命令currCMD=readCMDFromSocket(in);+ >"+"**currCMD===="+/**/if(currCMD.equals("1")){}elseif(currCMD.equals("2"))}elseif(currCMD.equals("3"))}elseif(currCMD.equals("4"))/**/try{out.write("servicereceiveOK".getBytes());}catch(IOExceptione){}件數據
/*接收文件數據,4字節(jié)文件長度,4byte[]filelength=newbyte[4];byte[]fileformat=newbyte[4];byte[]filebytes=null;/*從socket流中完整文件數據filebytes=receiveFileFromSocket(in,out,filelength,//Log.v(Service139.TAG,"receivedata="+//String(filebytes));try{/*Filefile=FileHelper.newFile("R0013340.JPG");FileHelper.writeFile(file,filebytes,0,}catch(IOExceptione){}}elseif(currCMD.equals("exit"))}}catch(Exceptione)//try//out.write("error".getBytes("utf-////}catch(IOExceptione1)////+ >"+"readwrite}}}catch(Exceptione)+ >"+"readwrite}finallytryif(client!=null)+ >"+}}catch(IOExceptione)+ >"+"readwrite}}判斷,不能用“-1”來判斷,因為“-1”socket關閉時才作為判斷結尾。socketout.write(bytes);socket的緩存,socket自動分包發(fā)android端接收數據的代碼:viewplaincopyto功能:從socket流中完整文件數*InputStreamin:socketbyte[]filelength:流的前4個字節(jié)要轉送的文件的字節(jié)byte[]fileformat:流的前5-8字節(jié)要轉送的文件的格式(如publicstaticbyte[]receiveFileFromSocket(InputStreamin,OutputStreamout,byte[]filelength,byte[]fileformat){bytefilebytesnull;//tryintfilelenMyUtil.bytesToInt(filelength);//4字節(jié)byte[]IntStringstrtmp="readfilelengthok:"+filelen;filebytes=newbyte[filelen];intpos=0;intrcvLen=while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){pos+=rcvLen;}+ >"+"readfileOK:filesize="+out.write("readfileok".getBytes("utf-8"));}catch(Exceptione)+ >"+"receiveFileFromSocket}
return}功能:從socket流中完整文件數*InputStreamin:socketbyte[]filelength:流的前4個字節(jié)要轉送的文件的字節(jié)byte[]fileformat:流的前5-8字節(jié)要轉送的文件的格式(如publicstaticbyte[]receiveFileFromSocket(InputStreamin,OutputStreamout,byte[]filelength,byte[]fileformat){byte[]filebytesnull;//tryintfilelenMyUtil.bytesToInt(filelength);//4字節(jié)byte[]IntStringstrtmp="readfilelengthok:"+filelen;filebytes=newbyte[filelen];intpos=0;intrcvLen=while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){pos+=rcvLen;}+ >"+"readfileOK:filesize="+out.write("readfileok".getBytes("utf-8"));}catch(Exceptione)+ >"+"receiveFileFromSocket}return}socket的最重要的機制就是讀寫采用的是阻塞的方式,如果客戶端作為命令發(fā)起者,服務器端作為接收者的話,只有當客戶端client用out.writer()寫到輸出流里后,即流中有數據servicereadread()那里等數據。還要讓服務器端可以同時連接多個client,即服務器端用newthread()來作數據操作??蛻舳耍╬c端viewplaincopytoclipboardprint?importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;import.InetAddress;import.Socket;.UnknownHostException;publicclasstestPcClient{@param@throwspublicstaticvoidmain(String[]args)throwsInterruptedException{try{"adbsambroadcast-aNotifyServiceStop");Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");"adbsambroadcast-aNotifyServiceStart");}catch(IOExceptione3){}Socketsocket=try
InetAddressserverAddr=serverAddr=InetAddress.getByName("");System.out.println("TCP1111"+"C:Connecting...");socket=newSocket(serverAddr,12580);Stringstr="hi,wufenglong";System.out.println("TCP221122"+"C:RECEIVE");BufferedOutputStreamout=newBufferedInputStreamin=newBufferedReaderbr=newBufferedReader(newInputStreamReader(booleanflag=true;while(flag){System.out.print("1~6的數字,StringstrWordbr.readLine();//1~6if(strWord.equals("1")){System.out.println("1finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);}elseif(strWord.equals("2"))System.out.println("2finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);}elseif(strWord.equals("3"))System.out.println("3finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+
}elseif(strWord.equals("4"))/*發(fā)送命令*/System.out.println("sendfilefinishsendingthe/*StringstrFormsocket=readFromSocket(in);.println("servicereadyreceice+byte[]filebytes=FileHelper.readFile("R0013340.JPG");System.out.println("filesize="+filebytes.length);/*4字節(jié)byte*/byte[]filelength=newbyte[4];filelength=/*將.apk4byte*/byte[]fileformat=null;fileformat=".apk".getBytes();.println("fileformatlength="+/*4字節(jié)為文件長度,4/*writebyte[]socket去,所以對方要循環(huán)寫完Stringstrok1=readFromSocket(in);System.out.println("servicereceivefilelength:"+strok1);//////Stringstrok2=//System.out.println("servicereceivefileformat:"http://System.out.println("writedatatoandroid");/*服務器反饋:接收成功*/StringstrreadreadFromSocket(in);System.out.println("senddatasuccess:"+strread);
}elseif(strWord.equalsIgnoreCase("EXIT")){System.out.println("EXITfinishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);flag=false;}}}catch(UnknownHostExceptione1)System.out.println("TCP331133"+"ERROR:"+}catch(Exceptione2)System.out.println("TCP441144"+"ERROR:"+}finallytryif(socket!=null){}}catch(IOExceptione)System.out.println("TCP5555"+"ERROR:"+}}}/*InputStreampublicstaticStringreadFromSocket(InputStreamin){intMAX_BUFFER_BYTES=4000;Stringmsg=byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];try{intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"utf-8");tempbuffer=}catch(Exceptione){}//Log.v(Service139.TAG,"msg="+msg);returnmsg;}}importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;import.InetAddress;import.Socket;.UnknownHostException;publicclasstestPcClient{@param@throwspublicstaticvoidmain(String[]args)throwsInterruptedException{try{"adbsambroadcast-aNotifyServiceStop");Runtime.getRuntime().exec("adbforwardtcp:12580tcp:10086");"adbsambroadcast-aNotifyServiceStart");}catch(IOExceptione3){}Socketsocket=null;try{InetAddressserverAddr=serverAddr=InetAddress.getByName("");System.out.println("TCP1111"+"C:Connecting...");socket=newSocket(serverAddr,12580);Stringstr="hi,wufenglong";System.out.println("TCP221122"+"C:RECEIVE");BufferedOutputStreamout=newBufferedInputStreamin=newBufferedReaderbr=newBufferedReader(newInputStreamReader(booleanflag=true;while(flag){System.out.print("1~6的數字,StringstrWordbr.readLine();//1~6if(strWord.equals("1")){System.out.println("1finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);}elseif(strWord.equals("2"))System.out.println("2finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);}elseif(strWord.equals("3"))System.out.println("3finishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserveris:\r\n"+strFormsocket);}elseif(strWord.equals("4"))/*發(fā)送命令*/System.out.println("sendfilefinishsendingthe/*服務器反饋:準備接收StringstrFormsocket=readFromSocket(in);.println("servicereadyreceice+byte[]filebytes=FileHelper.readFile("R0013340.JPG");System.out.println("filesize="+filebytes.length);/*4字節(jié)byte*/byte[]filelength=newbyte[4];filelength=/*將.apk4byte*/byte[]fileformat=null;fileformat=".apk".getBytes();.println("fileformatlength="+/*4字節(jié)為文件長度,4/*writebyte[]socket的緩存,系統(tǒng)自動分包寫過去,所以對方要循環(huán)寫完*/Stringstrok1=readFromSocket(in);System.out.println("servicereceivefilelength:"+strok1);//////Stringstrok2=//System.out.println("servicereceivefileformat:"http://System.out.println("writedatatoandroid");/*服務器反饋:接收成功*/StringstrreadreadFromSocket(in);System.out.println("senddatasuccess:"+strread);}elseif(strWord.equalsIgnoreCase("EXIT")){System.out.println("EXITfinishsendingthedata");StringstrFormsocket=readFromSocket(in);System.out.println("thedatasentbyserver+strFormsocket);flag=false;}}}catch(UnknownHostExceptione1)System.out.println("TCP331133"+"ERROR:"+}catch(Exceptione2)System.out.println("TCP441144"+"ERROR:"+}finallytryif(socket!=null){}}catch(IOExceptione)System.out.println("TCP5555"+"ERROR:"+}}}/*InputStreampublicstaticStringreadFromSocket(InputStreamin){intMAX_BUFFER_BYTES=4000;Stringmsg=byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];try{intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"utf-8");tempbuffer=}catch(Exceptione){}//Log.v(Service139.TAG,"msg="+msg);returnmsg;}}androidviewplaincopytoclipboardprint?packagecom.otheri.service;importimportjava.io.IOException;.ServerSocket;import.Socket;importimportandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.IBinder;import設置:android**publicclassandroidServiceextendsService{publicstaticfinalStringTAG="TAG";publicstaticBooleanmainThreadFlag=true;publicstaticBooleanioThreadFlag=true;ServerSocketserverSocket=null;finalintSERVER_PORT=10086;FiletestFile;privatesysBroadcastReceiverpublicvoidonCreate(){Log.v(TAG,Thread.currentThread().getName()+"---->"+ /*創(chuàng)建類sysBroadcastReceiver并registerReceiver*/newThread()publicvoidrun()}privatevoiddoListen()Log.d(TAG,Thread.currentThread().getName()+ +"doListen()START");serverSocket=null;tryLog.d(TAG,Thread.currentThread().getName()+ +"doListen()newserverSocket");serverSocket=newServerSocket(SERVER_PORT);booleanmainThreadFlag=true;while(mainThreadFlag){Log.d(TAG,Thread.currentThread().getName()+ +"doListen()listen");Socketclient=serverSocket.accept();newThread(newThreadReadWriterIOSocket(this,}}catch(IOExceptione1)+ >"+"newserverSocket}}/*創(chuàng)建類sysBroadcastReceiver并registerReceiver*/privatevoidsysRegisterReceiver(){Log.v(TAG,Thread.currentThread().getName()+ +"sysRegisterReceiver");sysBR=newsysBroadcastReceiver();/*BroadcastReceiver*/IntentFilterfilter1=newIntentFilter();/*新的應用程序被安裝到了設備上的廣播*/registerReceiver(sysBR,}/*類:BroadcastReceiver用于接收系統(tǒng)事件privateclasssysBroadcastReceiverextendsBroadcastReceiverpublicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();//}elseif//}Log.v(TAG,Thread.currentThread().getName()+ +"sysBroadcastReceiver}}publicvoidonDestroy(){//關閉線程mainThreadFlagfalse;ioThreadFlag=false;//tryLog.v(TAG,Thread.currentThread().getName()+ +"serverSocket.close()");}catch(IOExceptione){}Log.v(TAG,Thread.currentThread().getName()+ +"****************}publicvoidonStart(Intentintent,intstartId)Log.d(TAG,Thread.currentThread().getName()+ >"+"}publicIBinderonBind(Intentarg0){Log.d(TAG," returnnull;}}packageimportimportjava.io.IOException;.ServerSocket;import.Socket;importimportandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.os.IBinder;import設置:android**publicclassandroidServiceextendsService{publicstaticfinalStringTAG="TAG";publicstaticBooleanmainThreadFlag=true;publicstaticBooleanioThreadFlag=true;ServerSocketserverSocket=null;finalintSERVER_PORT=10086;FiletestFile;privatesysBroadcastReceiverpublicvoidonCreate(){Log.v(TAG,Thread.currentThread().getName()+"---->"+ /*創(chuàng)建類sysBroadcastReceiver并registerReceiver*/newThread()publicvoidrun()}privatevoiddoListen()Log.d(TAG,Thread.currentThread().getName()+ +"doListen()START");serverSocket=null;tryLog.d(TAG,Thread.currentThread().getName()+ +"doListen()newserverSocket");serverSocket=newServerSocket(SERVER_PORT);booleanmainThreadFlag=true;while(mainThreadFlag){Log.d(TAG,Thread.currentThread().getName()+ +"doListen()listen");Socketclient=serverSocket.accept();newThread(newThreadReadWriterIOSocket(this,}}catch(IOExceptione1)+ >"+"newserverSocket}}/*創(chuàng)建類sysBroadcastReceiver并registerReceiver*/privatevoidsysRegisterReceiver(){Log.v(TAG,Thread.currentThread().getName()+ +"sysRegisterReceiver");sysBR=newsysBroadcastReceiver();/*BroadcastReceiver*/IntentFilterfilter1=newIntentFilter();/*新的應用程序被安裝到了設備上的廣播*/registerReceiver(sysBR,}/*類:BroadcastReceiver用于接收系統(tǒng)事件privateclasssysBroadcastReceiverextendsBroadcastReceiverpublicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();//}elseif//}Log.v(TAG,Thread.currentThread().getName()+ +"sysBroadcastReceiver}}publicvoidonDestroy(){//關閉線程mainThreadFlagfalse;ioThreadFlag=false;//tryLog.v(TAG,Thread.currentThread().getName()+ +"serverSocket.close()");}catch(IOExceptione){}Log.v(TAG,Thread.currentThread().getName()+ +"****************}publicvoidonStart(Intentintent,intstartId)Log.d(TAG,Thread.currentThread().getName()+ >"+"}publicIBinderonBind(Intentarg0){Log.d(TAG," returnnull;}}PCBroastcastserviceServiceBroadcastReceiver.javaviewplaincopytoclipboardprint?packageimportandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiver{privatestaticStringSTART_ACTION="NotifyServiceStart";privatestaticStringSTOP_ACTION="NotifyServiceStop";publicvoidonReceive(Contextcontext,Intentintent){Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiverStringaction=if(START_ACTION.equalsIgnoreCase(action)){context.startService(newIntent(context,androidService.class)); +"ServiceBroadcastReceiveronReceivestart}elseif(STOP_ACTION.equalsIgnoreCase(action)){context.stopService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiveronReceivestop}}}packageimportimportandroid.content.Context;importandroid.content.Intent;importandroid.util.Log;publicclassServiceBroadcastReceiverextendsBroadcastReceiver{privatestaticStringSTART_ACTION="NotifyServiceStart";privatestaticStringSTOP_ACTION="NotifyServiceStop";publicvoidonReceive(Contextcontext,Intentintent){Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiverStringaction=if(START_ACTION.equalsIgnoreCase(action)){context.startService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+ +"ServiceBroadcastReceiveronReceivestart}elseif(STOP_ACTION.equalsIgnoreCase(action)){context.stopService(newIntent(context,androidService.class));Log.d(androidService.TAG,Thread.currentThread().getName()+" +"ServiceBroadcastReceiveronReceivestop}}}socketThreadReadWriterIOSocket.javaviewplaincopytoclipboardprint?packageimportjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;import.Socket;importimportimportcom.otheri.util.FileHelper;importcom.otheri.util.MyUtil;socket*@authorpublicclassThreadReadWriterIOSocketimplementsRunnable{privateSocketclient;privateContextThreadReadWriterIOSocket(Contextcontext,Socketclient)this.client=client;this.context=context;}publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+ +"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PCmsg*/StringcurrCMD="";out=newBufferedOutputStream(client.getOutputStream());in=newBufferedInputStream(client.getInputStream());//testSocket();//socket方法androidService.ioThreadFlag=true;whileandroidService.ioThreadFlag)tryif(!client.isConnected()){}/*PC發(fā)來的數據+"---->"+"will /*currCMD=readCMDFromSocket(in);+ >"+"**currCMD===="+/**/if(currCMD.equals("1")){}elseif(currCMD.equals("2"))}elseif(currCMD.equals("3"))}elseif(currCMD.equals("4"))/**/try{out.write("servicereceiveOK".getBytes());}catch(IOExceptione){}件數據
/*接收文件數據,4字節(jié)文件長度,4byte[]filelength=newbyte[4];byte[]fileformat=newbyte[4];byte[]filebytes=null;/*從socket流中完整文件數據filebytes=receiveFileFromSocket(in,out,filelength,//Log.v(Service139.TAG,"receivedata="+//String(filebytes));try{/*Filefile=FileHelper.newFile("R0013340.JPG");FileHelper.writeFile(file,filebytes,0,}catch(IOExceptione){}}elseif(currCMD.equals("exit"))}}catch(Exceptione)//try//out.write("error".getBytes("utf-////}catch(IOExceptione1)////+ >"+"readwrite}}}catch(Exceptione)+ >"+"readwrite}finallytryif(client!=null)+ >"+}}catch(IOExceptione)+ >"+"readwrite}}}功能:從socket流中完整文件數*InputStreamin:socketbyte[]filelength:流的前4個字節(jié)要轉送的文件的字節(jié)byte[]fileformat:流的前5-8字節(jié)要轉送的文件的格式(如publicstaticbyte[]receiveFileFromSocket(InputStreamin,OutputStreamout,byte[]filelength,byte[]fileformat){bytefilebytesnull;//tryin.read(filelength);//intfilelenMyUtil.bytesToInt(filelength);//4字節(jié)byte[]IntStringstrtmp="readfilelengthok:"+filelen;filebytes=newbyte[filelen];intpos=0;intrcvLen=while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){pos+=rcvLen;}+ >"+"readfileOK:filesize="+out.write("readfileok".getBytes("utf-8"));}catch(Exceptione)+ >"+"receiveFileFromSocket}return}/*命令publicstaticStringreadCMDFromSocket(InputStreamin){intMAX_BUFFER_BYTES=2048;Stringmsg=byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];try{intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"utf-8");tempbuffer=null;}catch(Exceptione)+ >"+"readFromSocket}//Log.v(Service139.TAG,"msg="+msg);returnmsg;}}packageimportjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;import.Socket;importandroid.content.Context;importandroid.util.Log;importcom.otheri.util.FileHelper;importcom.otheri.util.MyUtil;socket*@authorpublicclassThreadReadWriterIOSocketimplementsRunnable{privateSocketclient;privateContextThreadReadWriterIOSocket(Contextcontext,Socketclient)this.client=client;this.context=context;}publicvoidrun()Log.d(androidService.TAG,Thread.currentThread().getName()+ +"aclienthasconnectedtoserver!");BufferedOutputStreamout;BufferedInputStreamin;try/*PCmsg*/StringcurrCMD="";out=newBufferedOutputStream(client.getOutputStream());in=newBufferedInputStream(client.getInputStream());//testSocket();//socket方法androidService.ioThreadFlag=true;whileandroidService.ioThreadFlag)tryif(!client.isConnected()){}/*PC+"---->"+"will /*讀操作命令currCMD=readCMDFromSocket(in);+ >"+"**currCMD===="+/**/if(currCMD.equals("1")){}elseif(currCMD.equals("2"))}elseif(currCMD.equals("3"))}elseif(currCMD.equals("4"))/**/try{out.write("servicereceiveOK".getBytes());}catch(IOExceptione){}件數據
/*接收文件數據,4字節(jié)文件長度,4byte[]filelength=newbyte[4];byte[]fileformat=newbyte[4];byte[]filebytes=null;/*從socket流中完整文件數據filebytes=receiveFileFromSocket(in,out,filelength,//Log.v(Service139.TAG,"receivedata="+//String(filebytes));try{/*Filefile=FileHelper.newFile("R0013340.JPG");FileHelper.writeFile(file,filebytes,0,}catch(IOExceptione){}}elseif(currCMD.equals("exit"))}}catch(Exceptione)//try//out.write("error".getBytes("utf-////}catch(IOExceptione1)////+ >"+"readwrite}}}catch(Exceptione)+ >"+"readwrite}finallytryif(client!=null)+ >"+}}catch(IOExceptione)+ >"+"readwrite}}}功能:從socket流中完整文件數*InputStreamin:socketbyte[]filelength:流的前4個字節(jié)要轉送的文件的字節(jié)byte[]fileformat:流的前5-8字節(jié)要轉送的文件的格式(如publicstaticbyte[]receiveFileFromSocket(InputStreamin,OutputStreamout,byte[]filelength,byte[]fileformat){byte[]filebytesnull;//tryin.read(filelength);//intfilelenMyUtil.bytesToInt(filelength);//4字節(jié)byte[]IntStringstrtmp="readfilelengthok:"+filelen;filebytes=newbyte[filelen];intpos=0;intrcvLen=while((rcvLen=in.read(filebytes,pos,filelen-pos))>0){pos+=rcvLen;}+ >"+"readfileOK:filesize="+out.write("readfileok".getBytes("utf-8"));}catch(Exceptione)+ >"+"receiveFileFromSocket}return}/*命令publicstaticStringreadCMDFromSocket(InputStreamin)intMAX_BUFFER_BYTES=Stringmsg=byte[]tempbuffer=newbyte[MAX_BUFFER_BYTES];try{intnumReadedBytes=in.read(tempbuffer,0,tempbuffer.length);msg=newString(tempbuffer,0,numReadedBytes,"utf-8");tempbuffer=null;}
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 人事合同終止協(xié)議書樣本
- 與建筑公司簽訂的建筑合同文件模板
- 買賣合同樣本簡單格式
- 二手摩托車買賣合同范本
- 上海市保障性住房買賣合同示例
- 個人消費借款抵押擔保合同
- 交通事故責任劃分合同協(xié)議
- 個人資產轉讓合同范例
- 交通銀行外匯融資合同樣本
- 中小學學生校園意外傷害賠償合同范本
- 三對三籃球賽記錄表
- 礦山電工知識點講解
- 物業(yè)公司服務質量檢查流程
- 中國心胸外科的歷史和現狀
- 人教版9年級全一冊英語單詞表
- 三門峽水利工程案例分析工程倫理
- 中國旅游地理區(qū)劃-京津冀旅游區(qū)
- “1+X”證書制度試點職業(yè)技能等級證書全名錄
- 《社會主義市場經濟理論(第三版)》第八章社會主義市場經濟調控論
- 交流伺服系統(tǒng)常見故障及處理分解課件
- 水土保持單元工程質量評定表
評論
0/150
提交評論