Android: UDP communication

Table of contents

1. Introduction

Three elements of network communication:

(1), IP address:

 IPv4: 

IPv6: 

IP address form:

 IP common commands:

IP address operation class:

(2), port:

(3) Agreement:  

UDP protocol:

Features of UDP communication: 

 2. Commonly used classes and their methods

 1. DatagramSocket class

Commonly used methods:

2. DatagramPacket class

Commonly used methods: 

3. InetAddress class

Commonly used methods:

 3. UDP example

 MainActivity:

 UdpTool :

 activity_main:

Permissions:

operation result:

1. Introduction

        UDP (User Datagram Protocol) is a connectionless transmission protocol that is commonly used in network communications for real-time applications such as audio, video streaming, and online gaming. Compared with TCP (Transmission Control Protocol), UDP has lower overhead and higher transmission speed, but does not provide reliability and error detection functions.

Three elements of network communication:

(1), IP address:

        IP address (Internet Protocol Address) is a set of numbers used to identify and locate devices on the network . It is one of the basic elements necessary for Internet communicationand is used to determine the path of data packets through the network .

The role of an IP address is to provide a unique identifier         for every device connected to the Internet , similar to how every home in the world has a different address for mail delivery. Through IP addresses, computers can identify each other and establish network communications.

   An IP address is divided into two parts: the network part and the host part . The network part identifies the network to which the device is connected, while the host part identifies the specific device on the network. 

        An IP address consists of a 32-bit or 128-bit binary number, usually represented in common usage as a group of four decimal digits, for example: 192.168.0.1. IPv4 (Internet Protocol version 4) addresses use 32 bits, while IPv6 (Internet Protocol version 6) addresses use 128 bits to meet the growing demand for Internet devices.

 IPv4: 

IPv6: 

IP address form:
  • Public network address, and private address ( for LAN use ) .
  • The address starting with 192.168. is a common LAN address, ranging from 192.168.0.0--192.168.255.255 , which is specially used within the organization.
 IP common commands:
  • ipconfig : View the local IP address
  • Ping IP address: Check whether the network is connected

Special IP address :

  • Local IP: 127.0.0.1 or localhost : It is called the loopback address or the local loopback address. It will only search for the current local machine. 
IP address operation class:
  •     InetAddress (below)

(2), port:

        A port is a number used to identify an application or service on a computer network. It is an important concept in network communications and is used to distinguish different network applications and services.

        In Internet Protocol (IP), each host has a unique IP address, and the port number is used to identify a specific application or service on that host. It can be thought of as a door through which communication with a specific application is possible.

        The port number is a 16-bit integer ranging from 0 to 65535. Among them, port numbers from 0 to 1023 are called " Well- known Ports " and are used to identify some common services, such as HTTP (port number 80), FTP (port number 21), etc. Port numbers between 1024 and 49151 are called "Registered Ports " and are used for some registered applications. Port numbers between 49152 and 65535 are called " Dynamic or Private Ports" and are usually dynamically assigned to client applications by the operating system.

        By using the source IP address, destination IP address, and port number, the communication path in the network can be uniquely determined. The sender sends data to a specific port of the target host, and the receiver receives and processes the data based on the target port.

        The role of the port is to enable multiple applications to communicate on the same device at the same time , so that data on the network can be correctly routed to the target application. By associating data packets with specific ports, network devices can deliver data to the correct application and enable communication between application layers.

        To summarize, a port is a number used in computer networks to identify different applications or services . It helps network devices route and deliver data correctly by working with IP addresses.

Note: The program we develop ourselves chooses to register the port, and two programs cannot have the same port number in one device, otherwise an error will occur.

(3) Agreement :  

        Protocol is a collection of rules and standards that define data communication in a computer network. It specifies how various devices in the network communicate, the structure of the data format, error handling and other details to ensure that information can be transmitted and interpreted in a specific way.

        In a computer network, different devices and applications need to follow the same protocol to communicate effectively. A protocol defines the rules and semantics of data exchange, allowing communicating parties to understand and interpret the data sent and received by each other.

There are many common network protocols, some of the important ones include:

  1. TCP/IP protocol: TCP/IP (Transmission Control Protocol/Internet Protocol) is the most basic protocol family of the Internet. It defines the transmission methods and rules of data in the network, including IP address allocation, data routing, data fragmentation, and errors. Detection and error correction, etc. The TCP/IP protocol suite includes multiple protocols, such as IP protocol, TCP protocol, UDP protocol, etc.

  2. HTTP protocol: HTTP (Hypertext Transfer Protocol) is an application layer protocol used to transmit hypertext data between web browsers and web servers. It defines the format and rules for browsers to send requests and servers to respond to requests, and is one of the most commonly used protocols for web applications.

  3. FTP protocol: FTP (File Transfer Protocol) is a protocol used for file transfer on the network. It defines the rules for file transfer between client and server, including connection establishment, authentication, file upload and download, etc.

  4. SMTP protocol: SMTP (Simple Mail Transfer Protocol) is a protocol used for email transmission. It specifies the transmission method, envelope format, message format, etc. of emails to ensure that emails can be delivered from the sender to the recipient.

  5. DNS protocol: DNS (Domain Name System) is a protocol that converts domain names into IP addresses. It provides a distributed naming system that maps human-readable domain names to computer-recognizable IP addresses and implements domain name resolution.

        These are just a few of the many network protocols, each with different functions and application areas. By adhering to common protocol standards, network devices and applications can communicate with each other and complete specific tasks. The use of protocols enables computer networks to operate efficiently and reliably and implement various functions and services.

UDP protocol:

  • UDP is a connectionless , unreliable transmission protocol.
  • Encapsulate the data source IP , destination IP and port into data packets without establishing a connection.
  • Each packet size is limited to 64KB
  • The sender does not care whether the other party is ready or not, and the receiver does not confirm receipt, so it is unreliable.
  • It can be sent by broadcast, and there is no need to release resources when the data is sent. The overhead is small and the speed is fast.

Features of UDP communication: 

  1. Connectionless : UDP is a connectionless transport protocol, meaning there is no need to establish a connection before sending data. Each packet is independent and sent directly from the source host to the destination host.
  2. Fast speed : UDP does not have a handshake process and other control mechanisms like TCP, so the transmission speed is faster.
  3. Simple : Compared with TCP, the UDP protocol is simpler and has less header overhead.
  4. Unreliable : UDP does not provide reliability guarantees because it does not handle lost, duplicate, or out-of-order packets. This means that there may be a risk of packet loss during data transmission.
  5. Suitable for real-time applications : Due to UDP's fast transmission and low latency, it performs well in applications that require high real-time performance, such as voice calls, video streaming, etc.

 2. Commonly used classes and their methods

 1. DatagramSocket class

    DatagramSocketClass represents a UDP socket for sending and receiving datagrams. It provides methods related to underlying network communication. 

Commonly used methods:

  • DatagramSocket():Creates a new socket not bound to any local address and port.
  • DatagramSocket(int port):Creates a new socket bound to the specified local port.
  • void send(DatagramPacket packet): Send the specified data packet to the target host.
  • void receive(DatagramPacket packet): Receive packets from the socket.

2. DatagramPacket class

    DatagramPacketClass represents a UDP packet containing the data to be sent or received and the address and port number of the destination host.

Commonly used methods: 

  • DatagramPacket(byte[] data, int length):Creates a packet with no sending address or port number using the specified data and length.
  • DatagramPacket(byte[] data, int offset, int length):Creates a packet with no sending address or port number using the specified data, offset and length.
  • DatagramPacket(byte[] data, int offset, int length, InetAddress address, int port):Creates a packet using the specified data, offset, length, destination host address, and port number.
  • byte[] getData(): Get the data of this packet.
  • InetAddress getAddress(): Get the destination host address of the packet.
  • int getPort(): Get the destination port number of the packet.

3. InetAddress class

   InetAddressThe class represents an IP address and provides methods related to the IP address.

Commonly used methods:

  • public static InetAddress getLocalHost(): Returns the address object of this host.  
  • public static InetAddress getByName​(String host): Get the IP address object of the specified host. The parameter is the domain name or IP address.
  • public String getHostName​(): Get the host name of this IP address.
  • public String getHostAddress​(): Returns the IP address string.
  • public boolean isReachable ( int timeout): Connect to the host corresponding to the IP address within the specified milliseconds , and the connection returns true.

 3. UDP example

 MainActivity:

package com.example.udpdemo;



import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    Button sendBtn, decideBtn;
    EditText sendMsg, ipEd;
    TextView receiveMsg;
    // 对方的ip地址
    String ip;
    UdpTool udpTool;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        // 发送信息的函数
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在Android通信协议必须要放在线程里面进行
                String str = sendMsg.getText().toString();
                Log.v("发送", str);
                if (ip!=null){
                    udpTool.sendMessage(str,ip);
                }else {
                    Toast.makeText(MainActivity.this, "请输入对方ip和端口", Toast.LENGTH_SHORT).show();
                }
            }

        });
        decideBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ip = ipEd.getText().toString();
                Toast.makeText(MainActivity.this, "确定成功!", Toast.LENGTH_SHORT).show();
            }
        });
        // 接收信息的函数
        try {
            udpTool.receiveMessage(receiveMsg);;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initView() {
        sendBtn = findViewById(R.id.send_btn);
        sendMsg = findViewById(R.id.send_message);
        receiveMsg = findViewById(R.id.receive_message);
        ipEd = findViewById(R.id.target_ip_ed);
        decideBtn = findViewById(R.id.decide_btn);
        udpTool = new UdpTool(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        udpTool.closeSocket();
    }
}

 UdpTool :

package com.example.udpdemo;

import android.content.Context;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

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

public class UdpTool {
    private String TAG = "UdpTool";
    DatagramSocket mSocket;
    Context context;
    public UdpTool(Context context){
        this.context = context;
    }
    /**
     * 发送信息
     * @param msg 信息内容
     * @param ip 对方ip地址
     */
    public void sendMessage(String msg, String ip){
        // 需要开线程来发数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mSocket == null){
                    try {
                        // 这个是本机的端口号
                        mSocket = new DatagramSocket(20010);

                    } catch (SocketException e) {
                        e.printStackTrace();
                    }
                }
                // 将字符串转换成字节流,因为底层的传输都是字节传输
                byte[] data = msg.getBytes();
                try {
                    // 对方ip和端口
                    DatagramPacket pack = new DatagramPacket(data, data.length, InetAddress.getByName(ip), 60011);
                    mSocket.send(pack);
                    Log.d(TAG, "发送成功!");
                } catch (IOException e) {
                    Log.d(TAG, "发送失败!");
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 接收消息的函数
     */
    public void receiveMessage(TextView tv) throws Exception {
        // 创建线程,同理,接收信息也要放在线程里面接收
        new Thread(new Runnable() {
            public void run() {
                try {
                    if (mSocket == null) {
                        mSocket = new DatagramSocket(60011);
                    }
                    String str;
                    while (true) {
                        // 创建一个空的字节数组
                        byte[] data = new byte[1024];
                        // 将字节数组和数组的长度传进DatagramPacket 创建的对象里面
                        DatagramPacket pack2 = new DatagramPacket(data, data.length);
                        Log.v("s", "pack2");
                        Log.v("s", "开始 接收");
                        try {
                            // socket对象接收pack包,程序启动的时候,socket会一直处于阻塞状态,直到有信息传输进来
                            mSocket.receive(pack2);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        // 获取发送数据的IP地址
                         String ip = pack2.getAddress().getHostAddress();
                        // 获取发送数据端的端口号
                         int port = pack2.getPort();
                        str = new String(pack2.getData(), 0, pack2.getLength()); // 将字节数组转化成字符串表现出来
                        // 开启接收端口后会持续接收数据,只有页面可见的时候才将收到的数据写入
                            tv.setText(str);
                        Toast.makeText(context, "IP地址:"+ip+"端口:"+port, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 关闭通信
     */
    public void closeSocket() {
        if (mSocket != null) {
            mSocket.close();
            mSocket = null;
        }
    }
}

 activity_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:text="对方IP地址:"/>
        <EditText
            android:id="@+id/target_ip_ed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:textSize="20sp"/>
    </LinearLayout>

        <Button
            android:id="@+id/decide_btn"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="20sp"
            android:text="确定"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:orientation="vertical"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:text="发送信息端:"/>

        <EditText
            android:id="@+id/send_message"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:textSize="20sp"
            android:hint="发送的消息"
            android:background="@color/teal_200"
            android:gravity="center"/>
        <Button
            android:id="@+id/send_btn"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="20sp"
            android:text="发送"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:orientation="vertical"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:text="接收信息端:"/>


        <TextView
            android:id="@+id/receive_message"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:hint="接收到的消息"
            android:textSize="20sp"
            android:background="@color/purple_500"
            android:gravity="center"/>
    </LinearLayout>




</LinearLayout>

Permissions:

<uses-permission android:name="android.permission.INTERNET"/>

operation result:

Guess you like

Origin blog.csdn.net/A125679880/article/details/132134645