android UDP通信

男儿欲遂平生志,五经勤向窗前读。这篇文章主要讲述android UDP通信相关的知识,希望能为你提供帮助。
Android  UDP通信很简单的,调用下面这个方法就可以实现客户端和服务端的UDP通信,
 
只需要把要发给服务器的数据转成一个byte数组格式传进去就行了。
 
【android UDP通信】 

/**客户端向服务器端发送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=https://www.songbingjia.com/android/new String(receivePacket.getData()); Log.i("TAG","返回数据:"+receiveData); }else{ Log.i("TAG","NO response -- giving up"); } socket.close(); }catch (Exception e){ e.printStackTrace(); } } }.start(); }


    推荐阅读