gpt4 book ai didi

java - 如何接收来自服务器的 UDP 数据包?对于安卓 Java

转载 作者:行者123 更新时间:2023-12-03 11:54:02 24 4
gpt4 key购买 nike

我使用了一个线程来接收 UDP 数据包。当我向该特定 IP 发送数据包时,UDP 接收程序将在该 IP 运行。不幸的是,该应用程序将被停止。然后,如果我删除名为 new Thread(new Runnable())public void run 的线程,应用程序将运行良好,但只收到一个数据。我的 Intent 是在数据到来时在接收端连续接收数据。请认可我。

udpserver.java:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class UdpServer extends Activity {
/** Called when the activity is first created. */
private TextView data;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
data = (TextView) findViewById(R.id.textView);

runUdpServer();

}
private static final int UDP_SERVER_PORT = 11111;
private static final int MAX_UDP_DATAGRAM_LEN = 1500;
private void runUdpServer() {
new Thread(new Runnable() {
public void run() {
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds=null;
try {
ds = new DatagramSocket(UDP_SERVER_PORT);
//disable timeout for testing
//ds.setSoTimeout(100000);
ds.receive(dp);
lText = new String(dp.getData());
Log.i("UDP packet received", lText);
data.setText(lText);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (ds != null) {
ds.close();
}
}
}
}).start();
}

最佳答案

这是我用来接收和解析 UDP 数据包的工作 fragment 。

  try {
int port = 11000;

DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

while (true) {

dsocket.receive(packet);
lText = new String(buffer, 0, packet.getLength());
Log.i("UDP packet received", lText);
data.setText(lText);

packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}

关于java - 如何接收来自服务器的 UDP 数据包?对于安卓 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912939/

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