Home > Java > javaTutorial > body text

Detailed explanation of the sender and receiver examples of simulating UDP transmission in Java

黄舟
Release: 2017-03-28 10:18:10
Original
1914 people have browsed it

This article mainly introduces relevant information about the detailed explanation of the sender and receiver instances of simulated UDP transmission in java. Friends in need can refer to

The sender and receiver of simulated UDP transmission in java Detailed explanation of the receiving end example

1. Create the sending end of UDP transmission

1. Establish the UDP Socket service;

2. Encapsulate the data to be sent into a data packet;

3. Send the data packet through the UDP Socket service;

4. Close the 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("发送端启动......");

  // 1、创建UDP的Socket,使用DatagramSocket对象
  DatagramSocket ds = new DatagramSocket();

  // 2、将要发送的数据封装到数据包中
  String str = "UDP传输演示:I'm coming!";

  byte[] buf = str.getBytes(); //使用DatagramPacket将数据封装到该对象的包中

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

  // 3、通过UDP的Socket服务将数据包发送出去,使用send方法
  ds.send(dp);

  // 4、关闭Socket服务
  ds.close();
 }
}
Copy after login

2. Create a receiving end for UDP transmission

1. Establish a UDP Socket service. Because you want to receive data, you must specify a port number;

2. Create a data packet to store the received data and facilitate parsing the data using the data packet object method;

3. Use the receive method of the UDP Socket service Receive data and store it in the data packet;

4. Parse the data through the data packet method;

5. Close the 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("接收端启动......");

  // 1、建立UDP的Socket服务
  DatagramSocket ds = new DatagramSocket(10000);

  // 2、创建数据包
  byte[] buf = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf, buf.length);

  // 3、使用接收方法将数据存储到数据包中
  ds.receive(dp); // 该方法为阻塞式的方法

  // 4、通过数据包对象的方法解析这些数据,例如:地址、端口、数据内容等
  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、关闭Socket服务
  ds.close();
 }
}
Copy after login

3. Optimize the sending and receiving ends of UDP transmission

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

1. On the sending end, create a BufferedReader and enter the content from the keyboard;

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

/**
*优化UDP传输的发送端
*/
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("发送端启动......");

  // 创建UDP的Socket,使用DatagramSocket对象
  DatagramSocket ds = new DatagramSocket();

  BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
  String line = null;
  while ((line = bufr.readLine()) != null) {
   // 使用DatagramPacket将数据封装到该对象的包中
   byte[] buf = line.getBytes();
   DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000);
   // 通过UDP的Socket服务将数据包发送出去,使用send方法
   ds.send(dp);
   // 如果输入信息为over,则结束循环
   if ("over".equals(line))
    break;
  }
  // 关闭Socket服务
  ds.close();
 }
}
Copy after login
/**
*优化UDP传输的接收端
*/
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("接收端启动......");

  // 建立UDP的Socket服务
  DatagramSocket ds = new DatagramSocket(10000);

  while(true) {
   // 创建数据包
   byte[] buf = new byte[1024];
   DatagramPacket dp = new DatagramPacket(buf, buf.length);

   // 使用接收方法将数据存储到数据包中
   ds.receive(dp); // 该方法为阻塞式的方法

   // 通过数据包对象的方法解析这些数据,例如:地址、端口、数据内容等
   String ip = dp.getAddress().getHostAddress();

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

4. Create a chat room

According to the relevant properties of UDP (User Datagram Protocol, User Datagram Protocol), we can further create a simple UDP-based transmission The chat room under the agreement realizes the function of interactive chat.

/**
*创建UDP传输下的聊天室发送端
*/
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("对不起,发生错误啦!");
  }
 }
}
Copy after login
/**
*创建UDP传输下的聊天室接收端
*/
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+"......退出聊天室!");
    }
   }
  } catch (Exception e) {
   System.out.println("对不起,发生错误啦!");
  }
 }
}
Copy after login
/**
*创建UDP传输下的聊天室
*/
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();
 }
}
Copy after login

The above is the detailed content of Detailed explanation of the sender and receiver examples of simulating UDP transmission in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!