android UDP通信
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android UDP通信相关的知识,希望对你有一定的参考价值。
Android UDP通信很简单的,调用下面这个方法就可以实现客户端和服务端的UDP通信,
只需要把要发给服务器的数据转成一个byte数组格式传进去就行了。
/**客户端向服务器端发送UDP数据*/ public static void sendUdpData(final byte[] bytesToSend) { new Thread(){ @Override public void run() { try{ //IP是服务器地址 InetAddress serverAddress = InetAddress.getByName(IP); //PORT是服务器端口号 int serverPort = PORT; DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(8000); //sendPacket发送的数据包 DatagramPacket sendPacket = new DatagramPacket(bytesToSend,bytesToSend.length,serverAddress,serverPort); //receivePacket返回的数据包 DatagramPacket receivePacket = new DatagramPacket(new byte[bytesToSend.length],bytesToSend.length); int tries = 0; boolean receivedResponse = false; do{ socket.send(sendPacket); try{ socket.receive(receivePacket); if(!receivePacket.getAddress().equals(serverAddress)){ throw new IOException("接收到未知来源的包"); } receivedResponse = true; }catch(InterruptedIOException e){ tries +=1; Log.i("TAG","Received:"+"Time out,"+(5-tries)); } }while((!receivedResponse)&&(tries > 5)); if(receivedResponse){ //在这里可以拿到服务器返回的数据 String receiveData=new String(receivePacket.getData()); Log.i("TAG","返回数据:"+receiveData); }else{ Log.i("TAG","NO response -- giving up"); } socket.close(); }catch (Exception e){ e.printStackTrace(); } } }.start(); }
以上是关于android UDP通信的主要内容,如果未能解决你的问题,请参考以下文章
Socket 通信原理(Android客户端和服务器以TCP&&UDP方式互通)