简体   繁体   English

UDP套接字是否需要像TCP套接字一样通过Accept Process?

[英]Does UDP socket need to go through the Accept Process like TCP sockets?

I'm working with UDP and i was wondering about the Accept Method when multiple machine need to connect to a server. 我正在使用UDP,当多台机器需要连接到服务器时,我想知道接受方法。 So far i was working with UDPCliente class, IPEndPoint class and BeginRecieve / EndRecieve Method to create a server where multiple machine can connect at the same time. 到目前为止,我正在使用UDPCliente类,IPEndPoint类和BeginRecieve / EndRecieve方法来创建一台服务器,其中多台机器可以同时连接。

My question is simple do i need to use Accept Method to handler incoming connection and create a new socket for each new connection ? 我的问题很简单,我是否需要使用Accept Method来处理传入连接并为每个新连接创建一个新套接字?

What is the best way to handler multiple connection with UDP ? 使用UDP处理多个连接的最佳方法是什么?

The code samples i've seen so far create a new UDPClient class and a IPEndPoint where the server is listening for connections after that, the code call the BeginRecieve passing a function where the data is recieved and then starts the process of BeginRecieve again. 到目前为止,我见过的代码示例创建了一个新的UDPClient类和一个IPEndPoint,服务器在此之后监听连接,代码调用BeginRecieve传递一个接收数据的函数,然后再次启动BeginRecieve进程。

These are the code samples i've been using so far: 这些是我目前使用的代码示例:

public static void receiveCallback(IAsyncResult ar)
{
    UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
    IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

    byte[] receiveBytes = u.EndReceive(ar, ref e);
    UdpState s = new UdpState();
    s.e = e;
    s.u = u;
    u.BeginReceive(new AsyncCallback(receiveCallback), s);
}

public static void receiveMessages()
{
    IPEndPoint e = new IPEndPoint(IPAddress.Any, 5050);
    UdpClient u = new UdpClient(e);
    UdpState s = new UdpState();

    s.e = e;
    s.u = u;
    u.BeginReceive(new AsyncCallback(receiveCallback), s);
}

UDP is connectionless, so there's nothing to accept. UDP是无连接的,所以没有什么可以接受的。 If you need connections over UDP, then you have to implement them. 如果需要通过UDP进行连接,则必须实现它们。 Ideally, you would assign each "connection" some kind of identifier and include it in each datagram sent to the server. 理想情况下,您可以为每个“连接”分配某种标识符,并将其包含在发送到服务器的每个数据报中。 In some cases, it may be sufficient just to rely on the IP address and port to identify "connections". 在某些情况下,仅依靠IP地址和端口来识别“连接”就足够了。

But you can do it however you want. 但你可以随心所欲地做到这一点。 UDP treats each datagram as independent. UDP将每个数据报视为独立的。

Short answer - no, you don't use accept() with UDP. 简短的回答 - 不,你不使用UDP的accept()

In UDP there are no connections, only datagrams. 在UDP中没有连接,只有数据报。 One side sends them and the other might receive them. 一方发送它们,另一方可能接收它们。 Each datagram has information about the sender (IP address and port) that your server app can extract to differentiate the clients. 每个数据报都包含有关您的服务器应用程序可以提取以区分客户端的发件人(IP地址和端口)的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM