gpt4 book ai didi

安卓 : Receive data in UDP/TCP

转载 作者:可可西里 更新时间:2023-11-01 02:43:50 26 4
gpt4 key购买 nike

在我的 Android 应用程序中,我必须从 Wifi 连接(UDP 和 TCP)获取数据。

这是我的 UDP 代码:

try {
// Create new UDP-Socket
socket = new DatagramSocket(SERVERPORT);

while (isRunning) {

byte[] buf = new byte[50];
DatagramPacket packet = new DatagramPacket(buf,
buf.length);
socket.receive(packet);
String str = new String(buf, 0, packet.getLength());
packet.setLength(buf.length);

Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("getStr", str);
msg.setData(b);
handler.sendMessage(msg);

}

对于 TCP:

try {
s = new Socket(SERVERIP, SERVERPORT);

BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));

while (!s.isClosed()) {

String strTcp = in.readLine().toString();
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("getStr", strTcp + "\n");
msg.setData(b);

handler.sendMessage(msg);

}

它工作正常,但我的问题是:

我的 Wifi 设备发送一个数据序列(总是相同的字符串序列),当我在 TCP 中收到 1250 个字符串时,我在 UDP 中只收到 400 个字符串。通常 UDP 不是比 TCP 工作得更快吗?

我在 iPhone 上尝试了相同的测试,它工作正常,UDP 获得的值与 TCP 一样多。

那么问题是什么?阻塞 UDP 函数 receive() 是问题所在吗?

谢谢!

编辑

我用不同的设备测试了代码:UDP 在 Samsung Galaxy Tab (Android 3.1) 上运行良好,我收到了所有数据,但在其他设备 (Android 4.0) 上我只收到了 1/3 的数据。

好像是硬件问题...

最佳答案

TCP 和 UDP 的主要区别在于 TCP 是:

.. provides reliable, ordered delivery of a stream of octets from a program on one computer to another program on another computer.

Wikipedia - TCP

而 UDP:

.. uses a simple transmission model with a minimum of protocol mechanism.1 It has no handshaking dialogues, and thus exposes any unreliability of the underlying network protocol to the user's program. As this is normally IP over unreliable media, there is no guarantee of delivery, ordering or duplicate protection.

Wikipedia - UDP

换句话说,如果您使用 UDP/数据报套接字,您将不得不自己实现握手/纠错。我还注意到在您的代码中,您为接收数据报套接字分配了一个大小为 50 的缓冲区。如果套接字接收到溢出缓冲区的数据,它将简单地返回一个完整的 50 字节缓冲区并忽略其余部分;溢出的数据丢失。

当您在 iPhone 上尝试时,您确定没有在幕后为您完成某种错误纠正吗? (本人没有iPhone开发经验)

关于安卓 : Receive data in UDP/TCP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com