男儿欲遂平生志,五经勤向窗前读。这篇文章主要讲述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(); }
推荐阅读
- Android 全局使用第三方字体
- Java嵌套try块
- Java嵌套接口
- Java捕获多个异常
- Java成员内部类
- Java Local内部类
- 检查SSD健康状况的7个最佳免费工具/软件合集推荐
- 什么是Resmon、用途以及如何启动它(介绍和指南)
- 如何在Windows 10中禁用必应(详细分步指南)