如何在Android中接收UDP数据?

时间:2012-07-18 08:06:59

标签: java android

我将数据从PC发送到Android。但我无法在Android中使用UDP接收数据。如何在Android中使用UDP接收数据?如何在android-display上看到收到的数据?任何人都可以帮助我吗?

代码在这里:

public class MainActivity extends Activity {
  EditText textOut;
  EditText port;
  int UDP_SERVER_PORT = 8255;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.main);
    try {
      int port = UDP_SERVER_PORT;
      Log.d("UDP", "Connecting..");
      DatagramSocket clientsocket = new DatagramSocket(port);
      byte[] receivebuf = new byte[1024];
      DatagramPacket receivepacket =
        new DatagramPacket(receivebuf,receivebuf.length);
      clientsocket.receive(receivepacket);
      String modifiedSentence = new String(receivepacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      clientsocket.close();
    } catch (Exception e) {
      Log.e("UDP", "C: Error", e);
    }
  };
}

1 个答案:

答案 0 :(得分:0)

为了查看收到的数据,让我们假设数据转换为字符串,然后您需要一个视图来设置其值等于接收的数据。这对你有意义吗?