码迷,mamicode.com
首页 > 移动开发 > 详细

android UDP通信

时间:2017-08-15 13:21:59      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:nts   override   int   服务器   android   art   length   add   data   

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通信

标签:nts   override   int   服务器   android   art   length   add   data   

原文地址:http://www.cnblogs.com/xiaoliu500/p/7364541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!