简体   繁体   English

使用UDP发送和接收

[英]Sending and Receiving with UDP

I am trying to implement data transfer between a back-end server and the android device which is a request from device to server for information and the server responds(UDP use because it is faster and the functionality of TCP isn't needed, I guess...) 我正在尝试在后端服务器和android设备之间实现数据传输,这是从设备到服务器的信息请求,并且服务器响应(UDP使用是因为它速度更快并且不需要TCP功能,我想...)

Where do I begin for implementing this? 我从哪里开始执行此操作? I have looked at the Android Docs for DatagramSocket/Packet/SocketImplFactory as well as InetAddress and SocketAddress. 我看过DatagramSocket / Packet / SocketImplFactory的Android文档以及InetAddress和SocketAddress。

Is this the right direction? 这是正确的方向吗? Right now I am using HTTP Post requests, is any of that code recyclable? 现在我正在使用HTTP Post请求,其中的任何代码都可以回收吗?

HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            if (fleetID != null) {
                nameValuePairs.add(new BasicNameValuePair("fleetID", fleetID));

            }
            nameValuePairs.add(new BasicNameValuePair("user", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
//TODO: response failure? need to ensure success
            HttpEntity resEntity = response.getEntity();

            String strEntity = EntityUtils.toString(resEntity);
            //Log.i("RESPONSE", strEntity);
            return (strEntity);

The server and Android components can both be written in Java using the the standard Java DatagramSocket class. 服务器和Android组件都可以使用标准Java DatagramSocket类用Java编写。 A quick example can be found here (in this instance it is sending a String from the command prompt: http://systembash.com/content/a-simple-java-udp-server-and-udp-client/ . Basically, you make a DatagramSocket instance with a given port number and you send/recieve the data as a byte[]. However, I would be careful with using UDP. TCP ensures that no data is lost when the file is sent, and therefore ensures that data is not corrupted as it is sent. 可以在此处找到一个简单的示例(在这种情况下,它是从命令提示符发送一个字符串: http : //systembash.com/content/a-simple-java-udp-server-and-udp-client/ 。您使用给定的端口号创建一个DatagramSocket实例,然后将数据作为字节发送/接收[]。但是,使用UDP时要小心,TCP确保在发送文件时不会丢失任何数据,从而确保了数据在发送时未损坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM