問題描述
Ці павінен UDP‑сокет праходзіць працэс прыняцця, як TCP‑сокеты? (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. 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.
My question is simple do i need to use Accept Method to handler incoming connection and create a new socket for each new connection ?
What is the best way to handler multiple connection with 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.
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);
}
‑‑‑‑‑
參考解法
方法 1:
UDP is connectionless, so there's nothing to accept. If you need connections over UDP, then you have to implement them. 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".
But you can do it however you want. UDP treats each datagram as independent.
方法 2:
Short answer ‑ no, you don't use accept()
with UDP.
In UDP there are no connections, only datagrams. 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.
(by Josker、David Schwartz、Nikolai Fetissov)