Detail of sending and receiving instances in java simulating UDP transmission

  • 2020-06-15 08:54:30
  • OfStack

Details of sending and receiving instances simulating UDP transmission in java

1. Create the sending end of UDP transmission

1. Establish Socket service of UDP;

2. The data to be sent is encapsulated in the packet;

3. Send packet through UDP's Socket service;

4. Shut down Socket service.


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

public class UDPSend {

 public static void main(String[] args) throws IOException {

  System.out.println(" Sender startup ......");

  // 1 , create, UDP the Socket , the use of DatagramSocket object 
  DatagramSocket ds = new DatagramSocket();

  // 2 The data to be sent is encapsulated in the packet 
  String str = "UDP Transmission demonstration: I'm coming!";

  byte[] buf = str.getBytes(); // use DatagramPacket Encapsulate the data in the package of the object 

  DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000);

  // 3 And through UDP the Socket The service sends the packet out and USES it send methods 
  ds.send(dp);

  // 4 , close Socket service 
  ds.close();
 }
}

2. Create a receiver for UDP transmission

1. Set up Socket service of UDP. Because it needs to receive data, it must specify 1 port number;

2. Create data packets to store the received data and make it easy to parse the data in the way of data packet objects;

3. The receive method of Socket service of UDP is used to receive data and store it in the packet;

4. Analyze the data by means of data packets;

5. Shut down Socket service.


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

public class UDPReceive {
 public static void main(String[] args) throws IOException {

  System.out.println(" Receiver start ......");

  // 1 , to set up the UDP the Socket service 
  DatagramSocket ds = new DatagramSocket(10000);

  // 2 , create data packets 
  byte[] buf = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf, buf.length);

  // 3 , using the receive method to store data into packets 
  ds.receive(dp); //  This method is a blocking method 

  // 4 , parse the data through the method of packet object, such as address, port, data content, etc 
  String ip = dp.getAddress().getHostAddress();
  int port = dp.getPort();
  String text = new String(dp.getData(), 0, dp.getLength());

  System.out.println(ip + ":" + port + ":" + text);

  // 5 , close Socket service 
  ds.close();
 }
}

3. Optimize the sending end and receiving end of UDP transmission

Since in the first two parts, we can only send (or receive) one message at a time and then shut down the service! Therefore, if we want to send multiple messages, we need to constantly modify the content sent on the sending side, and also need to restart the server, which is troublesome. In order to overcome the above shortcomings, we can optimize it, namely:

1. Create BufferedReader at the sending end and input content from the keyboard;

2. At the receiving end, add while(ture) loop to receive content continuously.


/**
* To optimize the UDP The sending end of the transmission 
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSend {
 public static void main(String[] args) throws IOException {

  System.out.println(" Sender startup ......");

  //  create UDP the Socket , the use of DatagramSocket object 
  DatagramSocket ds = new DatagramSocket();

  BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  String line = null;
  while ((line = bufr.readLine()) != null) {
   //  use DatagramPacket Encapsulate the data in the package of the object 
   byte[] buf = line.getBytes();
   DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000);
   //  through UDP the Socket The service sends the packet out and USES it send methods 
   ds.send(dp);
   //  If the input information is over , the loop ends 
   if ("over".equals(line))
    break;
  }
  //  Shut down Socket service 
  ds.close();
 }
}


/**
* To optimize the UDP The receiving end of the transmission 
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {
 public static void main(String[] args) throws IOException {

  System.out.println(" Receiver start ......");

  //  To establish UDP the Socket service 
  DatagramSocket ds = new DatagramSocket(10000);

  while(true) {
   //  Create packet 
   byte[] buf = new byte[1024];
   DatagramPacket dp = new DatagramPacket(buf, buf.length);

   //  Use the receive method to store data into packets 
   ds.receive(dp); //  This method is a blocking method 

   //  The data is parsed through the methods of the packet object, such as address, port, data content, and so on 
   String ip = dp.getAddress().getHostAddress();

   int port = dp.getPort();
   String text = new String(dp.getData(), 0, dp.getLength());
   System.out.println(ip + ":" + port + ":" + text);
  }
 }
}

Create a chat room

According to the related nature of UDP (User Datagram Protocol, user datagram protocol), we can go one step further and create a simple chat room based on UDP transmission protocol to realize interactive chat function.


/**
* create UDP Transmission under the chat room to send terminal 
*/
package chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Send implements Runnable {

 private DatagramSocket ds;

 public Send(DatagramSocket ds) {
  this.ds = ds;
 }

 public void run() {
  try {
   BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
   String line = null;
   while ((line = bufr.readLine()) != null) {
    byte[] buf = line.getBytes();
    DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.255"), 10001);
    ds.send(dp);
    if ("886".equals(line))
     break;
   }
   ds.close();
  } catch (Exception e) {
   System.out.println(" Sorry, there was a mistake! ");
  }
 }
}


/**
* create UDP Under the transmission of the chat room receiver 
*/
package chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Rece implements Runnable {

 private DatagramSocket ds;

 public Rece(DatagramSocket ds) {
  this.ds = ds;
 }

 public void run() {
  try {
   while (true) {
    byte[] buf = new byte[1024];
    DatagramPacket dp = new DatagramPacket(buf, buf.length);
    ds.receive(dp);
    String ip = dp.getAddress().getHostAddress();
    String text = new String(dp.getData(), 0, dp.getLength());
    System.out.println(ip + ":::" + text);
    if(text.equals("886")){
     System.out.println(ip+"...... Quit the chat room! ");
    }
   }
  } catch (Exception e) {
   System.out.println(" Sorry, there was a mistake! ");
  }
 }
}


/**
* create UDP Transmission under the chat room 
*/
package chat;

import java.io.IOException;
import java.net.DatagramSocket;

public class ChatRoom {
 public static void main(String[] args) throws IOException {
  DatagramSocket send = new DatagramSocket();
  DatagramSocket rece = new DatagramSocket(10001);
  new Thread(new Send(send)).start();
  new Thread(new Rece(rece)).start();
 }
}


Related articles: