Android通过Socket与服务器之间进行通信的示例
一、首先进行Server的编写:
publicclassSocketServer{ privatestaticSocketmSocket; publicstaticvoidmain(String[]argc){ try{ //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口 ServerSocketserverSocket=newServerSocket(12345); InetAddressaddress=InetAddress.getLocalHost(); Stringip=address.getHostAddress(); //2.调用accept()等待客户端连接 System.out.println("~~~服务端已就绪,等待客户端接入~,服务端ip地址:"+ip); mSocket=serverSocket.accept(); //3.连接后获取输入流,读取客户端信息 InputStreamis=null; InputStreamReaderisr=null; BufferedReaderbr=null; OutputStreamos=null; is=mSocket.getInputStream(); isr=newInputStreamReader(is,"UTF-8"); br=newBufferedReader(isr); Stringinfo=null; while((info=br.readLine())!=null){ System.out.println("客户端发送过来的信息"+info); if(info.equals(BackService.HEART_BEAT_STRING)){ sendmsg("ok"); }else{ sendmsg("服务器发送过来的信息"+info); } } mSocket.shutdownInput(); mSocket.close(); }catch(IOExceptione){ e.printStackTrace(); } } //为连接上服务端的每个客户端发送信息 publicstaticvoidsendmsg(Stringmsg){ PrintWriterpout=null; try{ pout=newPrintWriter(newBufferedWriter( newOutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true); pout.println(msg); }catch(IOExceptione){ e.printStackTrace(); } } }
二、对客户端的编写,主要用用AIDL进行Server和Client
AIDL的编写主要为以下三部分:
1、创建AIDL
1)、创建要操作的实体类,实现Parcelable接口,以便序列化/反序列化
2)、新建aidl文件夹,在其中创建接口aidl文件以及实体类的映射aidl文件
3)、Makeproject,生成Binder的Java文件
2、服务端
1)、创建Service,在其中创建上面生成的Binder对象实例,实现接口定义的方法
2)、在onBind()中返回
3、客户端
1)、实现ServiceConnection接口,在其中拿到AIDL类
2)、bindService()
3)、调用AIDL类中定义好的操作请求
IBackService.aidl文件
packagecom.example.dell.aidlservice; //Declareanynon-defaulttypesherewithimportstatements interfaceIBackService{ /** *Demonstratessomebasictypesthatyoucanuseasparameters *andreturnvaluesinAIDL. */ booleansendMessage(Stringmessage); }
Service的编写,命名为BackService
publicclassBackServiceextendsService{ privatestaticfinalStringTAG="danxx"; publicstaticfinalStringHEART_BEAT_STRING="HeartBeat";//心跳包内容 /** *心跳频率 */ privatestaticfinallongHEART_BEAT_RATE=3*1000; /** *服务器ip地址 */ publicstaticfinalStringHOST="172.16.50.115"; /** *服务器端口号 */ publicstaticfinalintPORT=12345; /** *服务器消息回复广播 */ publicstaticfinalStringMESSAGE_ACTION="message_ACTION"; /** *服务器心跳回复广播 */ publicstaticfinalStringHEART_BEAT_ACTION="heart_beat_ACTION"; /** *读线程 */ privateReadThreadmReadThread; privateLocalBroadcastManagermLocalBroadcastManager; /***/ privateWeakReferencemSocket; //ForheartBeat privateHandlermHandler=newHandler(); /** *心跳任务,不断重复调用自己 */ privateRunnableheartBeatRunnable=newRunnable(){ @Override publicvoidrun(){ if(System.currentTimeMillis()-sendTime>=HEART_BEAT_RATE){ booleanisSuccess=sendMsg(HEART_BEAT_STRING);//就发送一个\r\n过去如果发送失败,就重新初始化一个socket if(!isSuccess){ mHandler.removeCallbacks(heartBeatRunnable); mReadThread.release(); releaseLastSocket(mSocket); newInitSocketThread().start(); } } mHandler.postDelayed(this,HEART_BEAT_RATE); } }; privatelongsendTime=0L; /** *aidl通讯回调 */ privateIBackService.StubiBackService=newIBackService.Stub(){ /** *收到内容发送消息 *@parammessage需要发送到服务器的消息 *@return *@throwsRemoteException */ @Override publicbooleansendMessage(Stringmessage)throwsRemoteException{ returnsendMsg(message); } }; @Override publicIBinderonBind(Intentarg0){ returniBackService; } @Override publicvoidonCreate(){ super.onCreate(); newInitSocketThread().start(); mLocalBroadcastManager=LocalBroadcastManager.getInstance(this); } publicbooleansendMsg(finalStringmsg){ if(null==mSocket||null==mSocket.get()){ returnfalse; } finalSocketsoc=mSocket.get(); if(!soc.isClosed()&&!soc.isOutputShutdown()){ newThread(newRunnable(){ @Override publicvoidrun(){ try{ OutputStreamos=soc.getOutputStream(); Stringmessage=msg+"\r\n"; os.write(message.getBytes()); os.flush(); }catch(IOExceptione){ e.printStackTrace(); } } }).start(); sendTime=System.currentTimeMillis();//每次发送成数据,就改一下最后成功发送的时间,节省心跳间隔时间 }else{ returnfalse; } returntrue; } privatevoidinitSocket(){//初始化Socket try{ //1.创建客户端Socket,指定服务器地址和端口 Socketso=newSocket(HOST,PORT); mSocket=newWeakReference (so); mReadThread=newReadThread(so); mReadThread.start(); mHandler.postDelayed(heartBeatRunnable,HEART_BEAT_RATE);//初始化成功后,就准备发送心跳包 }catch(UnknownHostExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } /** *心跳机制判断出socket已经断开后,就销毁连接方便重新创建连接 * *@parammSocket */ privatevoidreleaseLastSocket(WeakReference mSocket){ try{ if(null!=mSocket){ Socketsk=mSocket.get(); if(!sk.isClosed()){ sk.close(); } sk=null; mSocket=null; } }catch(IOExceptione){ e.printStackTrace(); } } classInitSocketThreadextendsThread{ @Override publicvoidrun(){ super.run(); initSocket(); } } //ThreadtoreadcontentfromSocket classReadThreadextendsThread{ privateWeakReference mWeakSocket; privatebooleanisStart=true; publicReadThread(Socketsocket){ mWeakSocket=newWeakReference (socket); } publicvoidrelease(){ isStart=false; releaseLastSocket(mWeakSocket); } @Override publicvoidrun(){ super.run(); Socketsocket=mWeakSocket.get(); if(null!=socket){ try{ InputStreamis=socket.getInputStream(); byte[]buffer=newbyte[1024*4]; intlength=0; while(!socket.isClosed()&&!socket.isInputShutdown()&&isStart&&((length=is.read(buffer))!=-1)){ if(length>0){ Stringmessage=newString(Arrays.copyOf(buffer,length)).trim(); Log.e(TAG,message); //收到服务器过来的消息,就通过Broadcast发送出去 if(message.equals("ok")){//处理心跳回复 Intentintent=newIntent(HEART_BEAT_ACTION); mLocalBroadcastManager.sendBroadcast(intent); }else{ //其他消息回复 Intentintent=newIntent(MESSAGE_ACTION); intent.putExtra("message",message); mLocalBroadcastManager.sendBroadcast(intent); } } } }catch(IOExceptione){ e.printStackTrace(); } } } } @Override publicvoidonDestroy(){ super.onDestroy(); mHandler.removeCallbacks(heartBeatRunnable); mReadThread.release(); releaseLastSocket(mSocket); } }
MainActivity
publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener{ privateTextViewmResultText; privateEditTextmEditText; privateIntentmServiceIntent; privateIBackServiceiBackService; privateServiceConnectionconn=newServiceConnection(){ @Override publicvoidonServiceDisconnected(ComponentNamename){ iBackService=null; } @Override publicvoidonServiceConnected(ComponentNamename,IBinderservice){ iBackService=IBackService.Stub.asInterface(service); } }; classMessageBackReciverextendsBroadcastReceiver{ privateWeakReferencetextView; publicMessageBackReciver(TextViewtv){ textView=newWeakReference (tv); } @Override publicvoidonReceive(Contextcontext,Intentintent){ Stringaction=intent.getAction(); TextViewtv=textView.get(); if(action.equals(BackService.HEART_BEAT_ACTION)){ if(null!=tv){ Log.i("danxx","Getaheartheat"); tv.setText("Getaheartheat"); } }else{ Log.i("danxx","Getaheartheat"); Stringmessage=intent.getStringExtra("message"); tv.setText("服务器消息:"+message); } } } privateMessageBackRecivermReciver; privateIntentFiltermIntentFilter; privateLocalBroadcastManagermLocalBroadcastManager; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLocalBroadcastManager=LocalBroadcastManager.getInstance(this); mResultText=(TextView)findViewById(R.id.resule_text); mEditText=(EditText)findViewById(R.id.content_edit); findViewById(R.id.send).setOnClickListener(this); findViewById(R.id.send1).setOnClickListener(this); mReciver=newMessageBackReciver(mResultText); mServiceIntent=newIntent(this,BackService.class); mIntentFilter=newIntentFilter(); mIntentFilter.addAction(BackService.HEART_BEAT_ACTION); mIntentFilter.addAction(BackService.MESSAGE_ACTION); } @Override protectedvoidonStart(){ super.onStart(); mLocalBroadcastManager.registerReceiver(mReciver,mIntentFilter); bindService(mServiceIntent,conn,BIND_AUTO_CREATE); } @Override protectedvoidonStop(){ super.onStop(); unbindService(conn); mLocalBroadcastManager.unregisterReceiver(mReciver); } publicvoidonClick(Viewview){ switch(view.getId()){ caseR.id.send: Stringcontent=mEditText.getText().toString(); try{ booleanisSend=iBackService.sendMessage(content);//SendContentbysocket Toast.makeText(this,isSend?"success":"fail",Toast.LENGTH_SHORT).show(); mEditText.setText(""); }catch(RemoteExceptione){ e.printStackTrace(); } break; caseR.id.send1: newThread(newRunnable(){ @Override publicvoidrun(){ try{ acceptServer(); }catch(IOExceptione){ e.printStackTrace(); } } }).start(); break; default: break; } } privatevoidacceptServer()throwsIOException{ //1.创建客户端Socket,指定服务器地址和端口 Socketsocket=newSocket("172.16.50.115",12345); //2.获取输出流,向服务器端发送信息 OutputStreamos=socket.getOutputStream(); PrintWriterprintWriter=newPrintWriter(os);//将输出流包装为打印流 //获取客户端的IP地址 InetAddressaddress=InetAddress.getLocalHost(); Stringip=address.getHostAddress(); printWriter.write("客户端:~"+ip+"~接入服务器!!"); printWriter.flush(); socket.shutdownInput(); socket.close(); } }
源码地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。