This article talks about using udp to do a simple sending and receiving in Java.
Code 1: Sender-demo2Sender.java
package udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException;
In the java network communication industry As Socket (socket) communication, both devices required for communication must have Socket installed.
Different protocols have different sockets (Sockets)
Features of UDP communication protocol:
1. Encapsulate the data For data packets, connectionless oriented.
2. The size of each data packet is limited to 64K
3. Because there is no connection, it is unreliable
4. Because there is no need to establish a connection, it is fast
5. UDP communication is not divided into server and client, only sender and receiver.
For example: property management walkie-talkie, FeiQ chat, games...
Socket under udp protocol:
DatagramSocket (udp socket service )
DatagramPacket(data packet class)
DatagramPacket(buf, length, address, port)
buf: sent data content
length: sent The size of the data content.
address: the destination IP address object sent
port: the port number.
Steps for using the sender:
1. Establish udp service.
2. Prepare the data, encapsulate the data into a data packet and send it. The data packet from the sending end must carry the IP address and port number.
3. Call the udp service and send data.
4. Close the resource.
/发送端
@SuppressWarnings("unused")
public class demo1Sender {
public static void main(String[] args) throws IOException {
//建立udp的服务
DatagramSocket datagramSocket = new DatagramSocket();
//准备数据,把数据封装到数据包中。
String data = "这个是我第一个udp的例子..";
//创建了一个数据包
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length,InetAddress.getLocalHost() , 9090);
//调用udp的服务发送数据包
datagramSocket.send(packet);
//关闭资源 ---实际上就是释放占用的端口号
datagramSocket.close();
}
}Code 2: Receiver-demo1Receive.java
package udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket;
Receiver usage steps
1. Establish udp service
2. Prepare empty data packets to receive data.
3. Call the udp service to receive data.
4. Close the resource
public class demo1Receive {
public static void main(String[] args) throws IOException {
//建立udp的服务 ,并且要监听一个端口。
DatagramSocket socket = new DatagramSocket(9090);
//准备空的数据包用于存放数据。
byte[] buf = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); // 1024
//调用udp的服务接收数据
socket.receive(datagramPacket); //receive是一个阻塞型的方法,没有接收到数据包之前会一直等待。 数据实际上就是存储到了byte的自己数组中了。
System.out.println("接收端接收到的数据:"+ new String(buf,0,datagramPacket.getLength())); // getLength() 获取数据包存储了几个字节。
System.out.println("receive阻塞了我,哈哈");
//关闭资源
socket.close();
}
} [Recommended course: Java Video Tutorial]
The above is the detailed content of java-Use udp to do a simple sending and receiving. For more information, please follow other related articles on the PHP Chinese website!
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PMThe article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.
How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PMThe article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.
How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PMThe article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra
How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PMThe article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]
How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PMJava's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment






