繁体   English   中英

在Android中的数据报套接字上发送和接收UDP数据包

[英]sending and receiving UDP packet on datagram socket in android

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

    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());

}

先谢谢您的帮助。

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

解决此问题的方法:将网络代码复制到新的线程中,然后运行它。

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

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

暂无
暂无

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

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