浅谈Java和C#UDP通信

Java UDP高级用法示例

1. 多线程UDP服务器
java 复制代码
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
相关推荐
禾小西1 小时前
Java 逐梦力扣之旅_[204. 计数质数]
java·算法·leetcode
ゞ 正在缓冲99%…1 小时前
leetcode295.数据流的中位数
java·数据结构·算法·leetcode·
xy_optics3 小时前
用matlab探索卷积神经网络(Convolutional Neural Networks)-3
开发语言·matlab·cnn
有梦想的攻城狮3 小时前
spring-cloud-alibaba-nacos-config使用说明
java·spring·nacos·springcloud·配置中心
独好紫罗兰3 小时前
洛谷题单3-P1720 月落乌啼算钱(斐波那契数列)-python-流程图重构
开发语言·算法·leetcode
iOS技术狂热者3 小时前
wireshak抓手机包 wifi手机抓包工具
websocket·网络协议·tcp/ip·http·网络安全·https·udp
慕容莞青4 小时前
MATLAB语言的进程管理
开发语言·后端·golang
Yan-英杰4 小时前
【百日精通JAVA | SQL篇 | 第三篇】 MYSQL增删改查
java·数据库·sql
jimin_callon4 小时前
VBA第三十八期 VBA自贡分把表格图表生成PPT
开发语言·python·powerpoint·编程·vba·deepseek
矛取矛求6 小时前
C++ 标准库参考手册深度解析
java·开发语言·c++