编程知识 cdmana.com

Implementation of UDP LAN communication in Java and Android platform

LAN communication has been rarely mentioned by others , I've also tried to build a communication network with Bluetooth , There's a chance to try this time UDP LAN communication , Here we put some basic processes together in Android Record the problems on the platform .

1. UDP Basic knowledge of

1.1 What is? UDP

Internet The protocol set supports a connectionless transport protocol , This protocol is called user datagram protocol (UDP,User Datagram Protocol).UDP Provides an application with a way to send encapsulation without establishing a connection IP The method of datagram .RFC 768 It describes UDP.
Internet There are two main protocols in the transport layer of , Complement each other . Unconnected UDP, In addition to sending packet capabilities to applications and allowing them to architect their own protocols at the required level , Almost nothing special is done . Connection oriented is TCP, The agreement did almost everything .
——《 Baidu Encyclopedia 》

According to Baidu Encyclopedia ,UDP It's a data transfer protocol , For connectionless data transmission , It shows that the packet loss probability of this protocol is high , Not suitable for complex network environment .UDP The message has no reliability guarantee 、 Sequence guarantee and flow control fields, etc , Poor reliability . But because of UDP Protocol has fewer control options , Small delay in data transmission 、 High data transmission efficiency , Suitable for applications with low reliability requirements , Or applications that can guarantee reliability . In the LAN , The arrival rate of data is almost guaranteed , therefore UDP In LAN communication, we have more than TCP More important position .

1.2 UDP Basic communication flow

  1. Set a unified port number ;

  2. Initializes the data sink that binds the specified port number ;

  3. Specify the recipient's IP Address ;

  4. Prepare lightweight data ;

  5. Send data to the specified IP Address ;

  6. The data receiver triggers the subsequent logic .

2. UDP LAN communication Java Realization

2.1 UDP radio broadcast

UDP The implementation of broadcasting is relatively simple , Of the recipient IP The address is fixed to 255.255.255.255, Port number optional , Ensure that the slogan of the sender and the receiver are consistent and do not conflict with other programs , The code example is as follows :

public class UDPManager {

  public static final int BUFFER_SIZE = 2048;

  public DatagramSocket socket;

  public void init() {
    try {
      // First create a binding port number of 9527 Of DatagramSocket
      socket = new DatagramSocket(9527);
      // Turn on the data receiver 
      openReceiver();
      // Send broadcast messages 
      sendBroadcast("Hello World!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void openReceiver() {
    // Loop in the child thread to receive data 
    new Thread(new Runnable() {
      @override
      public void run() {
        byte[] buffer = new byte[BUFFER_SIZE];
        DatagramPacket dp = new DatagramPacket(buffer, BUFFER_SIZE);
        while(socket != null) {
          try {
            socket.receive(dp);
            System.out.println(new String(buffer));
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }).start;
  }

  public void sendBroadcast(String dataStr) throws IOException {
    // Send broadcast messages , The message is dataStr
    if (socket != null) {
      byte[] buffer = dataStr.getBytes();
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("255.255.255.255"), 9527);
      socket.send(packet);
    }
  }
}

2.2 UDP unicast

UDP The implementation of unicast is similar to broadcasting , Of the recipient IP When the address needs to send a message , Port number optional , Ensure that the slogan of the sender and the receiver are consistent and do not conflict with other programs , stay 2.1 The display in the UDPManager Class can be added with unicast sending method , The code example is as follows :

public class UDPManager {
  //···
  public void sendSingle(String dataStr, String targetIP) throws IOException {
    // Send a unicast message , The message is dataStr, The receiving party IP The address is targetIP
    if (socket != null) {
      byte[] buffer = dataStr.getBytes();
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(targetIP), 9527);
      socket.send(packet);
    }
  }
}

2.3 UDP multicast

UDP The implementation of multicast is similar to group chat , You need to add a specific IP Group of , Then the news goes to IP Just send ,, Port number optional , Unicast and multicast port numbers cannot be the same , Ensure that the slogan of the sender and the receiver are consistent and do not conflict with other programs , And need to be in 2.1 The display in the UDPManager Class MulticastSocket A member variable of type 、 modify init Methods and openReceiver Method 、 Add the corresponding multicast method , The code example is as follows :

public class UDPManager {
  //···
  // Multicast address optional , stay 224.0.1.0~238.255.255.255 Between 
  public static final String MULICAST_ADDRESS = "224.255.0.1"
  public MulticastSocket multiSocket;

  public void init() {
    try {
      // First create a binding port number of 9527 Of DatagramSocket
      socket = new DatagramSocket(9527);
      // Create a binding port number of 9528 Of MulticastSocket
      multiSocket = new MulticastSocket(9528);
      // Turn on the data receiver 
      openReceiver();
      // Join a multicast group 
      multiSocket.joinGroup(InetAddress.getByName(MULICAST_ADDRESS))
      // Send broadcast messages 
      sendBroadcast("Hello World!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void openReceiver() {
    //···
    // Create a new child thread to receive multicast data 
    new Thread(new Runnable() {
      @override
      public void run() {
        byte[] buffer = new byte[BUFFER_SIZE];
        DatagramPacket dp = new DatagramPacket(buffer, BUFFER_SIZE);
        while(multiSocket != null) {
          try {
            multiSocket.receive(dp);
            System.out.println(new String(buffer));
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }).start;
  }

  //···
  public void sendMultiple(String dataStr) throws IOException {
    // Sending multicast messages , The message is dataStr
    if (multiSocket != null) {
      byte[] buffer = dataStr.getBytes();
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(MULICAST_ADDRESS), 9528);
      multiSocket.send(packet);
    }
  }
}

2.4 The basic conception of LAN communication

In the above three kinds of UDP In the process of realizing communication mode , It is found that broadcast mode can not reach all receivers in LAN , Receivers not in the same network segment will not be able to receive broadcast messages , And unicast and multicast can cross the network segment .

A preliminary assumption , Just use multicast , LAN communication process is as follows :

  1. The user program starts ,UDP Initialization complete ;

  2. Join multicast , Send user online message , Expose local information (IP Address, etc );

  3. The receiver receiving the user's online message will add the user to the online user list , And send the local user online message again ;

  4. User triggers message sending , The message comes with native information (IP Address, etc ) With the designated recipient IP Address or user name, etc ( It could be an array , Specify multiple recipients );

  5. Receiver receives message , Determine whether there is a native in the specified receiver of this message , If so, process the message , Or throw it away ;

  6. The user closes the program , Send user offline message ;

  7. The receiver receiving the user's offline message will remove the user from the online user list .

3. Android Same platform wifi Try in the environment

3.1 UDP Problems in the way of communication

stay Android A preliminary attempt has been made on the platform UDP The various means of communication , It is found that multicast has been greatly affected , After multiple verification and multiple attempts to use multicast , Finally gave up in Android Multicast is used on the platform , If readers are interested, they can try to solve it .

3.2 Android wifi The basic conception of LAN communication

Refer to previous ideas , When multicast cannot be used , Broadcasting combined with unicast has become my alternative , The general flow is as follows :

  1. The user program starts ,UDP Initialization complete ;

  2. Send a broadcast , Transmission of user online messages , Expose local information (IP Address, etc );

  3. The receiver receiving the broadcast adds the user to the online user list , And send a local user online message to the user ;

  4. User triggers message sending , Sent to the designated receiver in unicast mode IP Address , The message comes with native information (IP Address, etc );

  5. Receiver receives message , Processing the message .

  6. The user closes the program , Send user offline message ;

  7. The receiver receiving the user's offline message will remove the user from the online user list .

版权声明
本文为[coder-ice]所创,转载请带上原文链接,感谢

Scroll to Top