import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadedUDPReceiver implements Runnable {
private int port;
private ExecutorService executorService;
public MultiThreadedUDPReceiver(int port, int numberOfThreads) {
this.port = port;
this.executorService = Executors.newFixedThreadPool(numberOfThreads);
}
@Override
public void run() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Message received: " + message);
executorService.submit(() -> processMessage(message));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
if (!executorService.isShutdown()) {
executorService.shutdown();
}
}
}
private void processMessage(String message) {
System.out.println("Processing message: " + message);
}
public static void main(String[] args) {
int port = 9876;
int numberOfThreads = 4;
Thread receiverThread = new Thread(new MultiThreadedUDPReceiver(port, numberOfThreads));
receiverThread.start();
}
}
2. 带校验和的UDP数据传输
java复制代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPChecksumExample {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
int port = 9876;
// 发送端:添加校验和
String message = "Hello, UDP!";
byte[] data = message.getBytes();
int checksum = calculateChecksum(data);
byte[] checksumBytes = intToBytes(checksum);
byte[] buffer = new byte[data.length + checksumBytes.length];
System.arraycopy(data, 0, buffer, 0, data.length);
System.arraycopy(checksumBytes, 0, buffer, data.length, checksumBytes.length);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(packet);
// 接收端:校验数据完整性
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);
byte[] receivedData = new byte[receivePacket.getLength() - 4];
byte[] receivedChecksumBytes = new byte[4];
System.arraycopy(receivePacket.getData(), 0, receivedData, 0, receivePacket.getLength() - 4);
System.arraycopy(receivePacket.getData(), receivePacket.getLength() - 4, receivedChecksumBytes, 0, 4);
int receivedChecksum = bytesToInt(receivedChecksumBytes);
int calculatedChecksum = calculateChecksum(receivedData);
if (receivedChecksum == calculatedChecksum) {
System.out.println("Data integrity verified.");
} else {
System.out.println("Data corruption detected.");
}
socket.close();
}
private static int calculateChecksum(byte[] data) {
int checksum = 0;
for (byte b : data) {
checksum += b;
}
return checksum;
}
private static byte[] intToBytes(int value) {
return new byte[]{
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) value
};
}
private static int bytesToInt(byte[] bytes) {
return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
}
}
C# UDP高级用法示例
1. 异步UDP服务器
cs复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class AsyncUdpServer
{
private const int Port = 5000;
static async Task Main(string[] args)
{
using (UdpClient udpClient = new UdpClient(Port))
{
Console.WriteLine("UDP Server is running...");
while (true)
{
try
{
UdpReceiveResult result = await udpClient.ReceiveAsync();
string receivedData = Encoding.UTF8.GetString(result.Buffer);
Console.WriteLine($"Received data from {result.RemoteEndPoint}: {receivedData}");
string responseData = "Message received!";
byte[] sendBytes = Encoding.UTF8.GetBytes(responseData);
await udpClient.SendAsync(sendBytes, sendBytes.Length, result.RemoteEndPoint);
}
catch