【问题标题】:sending and receiving UDP packet on datagram socket in android在android中的数据报套接字上发送和接收UDP数据包
【发布时间】:2013-08-28 03:04:51
【问题描述】:

我有两个类,一个是发送者类,另一个是接收者类。发送和接收应用程序都在几秒钟后停止并关闭。 我的发件人类别是:

    public class MainActivity extends Activity {
InetAddress receiverAddress;
DatagramSocket datagramSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    try {
        datagramSocket = new DatagramSocket(4444);
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    byte[] buffer = "0123456789".getBytes();
    byte[] address="192.168.1.101".getBytes();

    try {
        receiverAddress = InetAddress.getByAddress(address);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    DatagramPacket packet = new DatagramPacket(
            buffer, buffer.length, receiverAddress, 4444);

    try {
        datagramSocket.send(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

我的接收或听课是:

public class MainActivity extends Activity {
DatagramSocket datagramSocket;
DatagramPacket packet;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv1=(TextView)findViewById(R.id.textView1);
     try {
        datagramSocket = new DatagramSocket(80);
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    byte[] buffer = new byte[10];
     packet = new DatagramPacket(buffer, buffer.length);

    try {
        datagramSocket.receive(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] buff = packet.getData();

tv1.setText(buff.toString());

}

提前感谢您的帮助。

【问题讨论】:

  • 我认为您必须在单独的线程或新线程上运行这些数据报事务,尽管我不确定仅此一项是否能解决您的问题
  • 你的 logcat 里有什么?

标签: java android sockets udp udpclient


【解决方案1】:

在 Android 中,您不允许在 UIThread(主线程)上执行网络操作

要解决这个问题: 将您的网络代码复制到一个新线程并让它运行。

【讨论】:

    【解决方案2】:

    “new DatagramSocket(...)”调用中的端口号看起来很奇怪。客户端应该创建一个“未绑定”套接字 - 只需使用“new DatagramSocket();”。发送方应绑定到客户端发送到的端口,即“new DatagramSocket(4444);”。

    【讨论】:

    • 我认为你的意思是“接收者”应该绑定到“发送者”发送到的端口。
    【解决方案3】:

    源端口号和目标端口号应该相同。在“DatagramSocket(xxx)”中给出相同的数字。 xxx 在两个程序中必须相同。

    【讨论】:

    • 差不多但不完全。发送方的端口绑定无关紧要。在上面的代码中,发送方正在发送到端口 4444,而接收方正在侦听端口 80。这些都不能解释为什么应用程序会在几秒钟后停止。接收者应该无限期地阻塞等待一个永远不会到达的数据包。除非有人将网络浏览器指向它...
    猜你喜欢
    • 2017-08-17
    • 2010-11-13
    • 2012-10-03
    • 2012-05-20
    • 1970-01-01
    • 2013-11-19
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多