C#UDP数据包发送和接收

时间:2018-07-27 11:55:59

标签: c# sockets networking udp

我试图弄清楚如何使用C#作为客户端通过UDP协议发送和接收数据,并运行JS服务器,该服务器将传输“响应”数据包以进行测试。

下面是我为测试而制作的UDP类,它仅是2个线程:
一个从UDP读取接收到的数据,另一个从另一个线程发送数据。

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

using System.Threading;

namespace UDPTesting {

    class UDPHandler {

        private int receivePort, sendPort;
        private string serverIP;
        private IPEndPoint sendEndPoint, receiveEndPoint;

        public UDPHandler(string serverIP, int receivePort, int sendPort) {
            this.serverIP = serverIP;
            this.receivePort = receivePort;
            this.sendPort = sendPort;
            this.sendEndPoint = new IPEndPoint(IPAddress.Parse(this.serverIP), this.sendPort);
            this.receiveEndPoint = new IPEndPoint(IPAddress.Parse(this.serverIP), this.receivePort);
            this.readerUdpClient();
            this.senderUdpClient();
        }

        void readerUdpClient() {
            UdpClient readerClient = new UdpClient();
            IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, 3000);
            readerClient.Client.Bind(localEndpoint);          //Tried both Connect and Bind
            //readerClient.Connect(this.receiveEndPoint);
            Thread t = new Thread(() => {
                Console.WriteLine("Awaiting data from server...");
                var remoteEP = new IPEndPoint(IPAddress.Any, 3000);
                byte[] bytesReceived = readerClient.Receive(ref remoteEP);
                //The above throws:     System.InvalidOperationException: 'You must call the Bind method before performing this operation'
                Console.WriteLine("Received data from " + remoteEP.ToString());
            });
            t.Start();
        }

        void senderUdpClient() {
            UdpClient senderClient = new UdpClient();
            senderClient.Connect(this.sendEndPoint);
            string sendString = "1;2;3";
            byte[] bytes = toBytes(sendString);
            Thread t = new Thread(() => {
                while (true) {
                    senderClient.Send(bytes, bytes.Length);
                    Thread.Sleep(1000);
                }
            });
            t.Start();
        }

        public byte[] toBytes(string text) {
            return Encoding.UTF8.GetBytes(text);
        }

        public string fromBytes(byte[] bytes) {
            return Encoding.UTF8.GetString(bytes);
        }

    }
}

另外,我对程序的“主要”是这样:

using System;
using System.Threading;

namespace UDPTesting {

    class Program {

        static void Main(string[] args) {
            string serverIP = "46.101.102.243";
            int sendPort = 41234;
            int receivePort = 3000;
            UDPHandler handler = new UDPHandler(serverIP, receivePort, sendPort);
        }

    }

}

在将数据从客户端发送到服务器的同时,如何读取服务器在客户端中发送的响应?

我们分别进行了测试:

1)从客户端->服务器发送UDP数据包可以正常工作,因为我可以看到服务器收到了该数据包。

2)从服务器发送UDP数据包->客户端可以正常工作,因为我可以看到客户端收到了该数据包。

3)当客户端尝试同时发送和读取时,它将向服务器发送数据,但不会读取响应。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

您的接收功能应该像这样

void readerUdpClient()
{
    new Thread(() => {
        UdpClient readerClient = new UdpClient(receivePort);  
        Console.WriteLine("Awaiting data from server...");
        var remoteEP = new IPEndPoint(IPAddress.Any, 0);
        byte[] bytesReceived = readerClient.Receive(ref remoteEP);
        Console.WriteLine($"Received {bytesReceived.Length} bytes from {remoteEP}");
    }).Start();
}

占用端口的UdpClient constructor自动为您绑定本地端点。