简体   繁体   中英

About C# UDP Sockets

  • I am supposed to connect to external server using UDP sockets in C#..
  • I could not understand these 2 lines in server usage notes:

"Use of dedicated sockets is enforced."

and

"If the server looses UDP connectivity with the client, it will ..."

I thought that the UDP socket is connectionless! So what did "looses connectivity" mean? and how to avoid it? Does there is a known way to ensure "dedicated sockets"?

Thanks

"Use of dedicated sockets is enforced."

To me this says, create one unique socket for each connection and use it throughout that connection.

EDIT: Just to expand on this, from the servers point of view.

UDP sockets are not identified by the remote address, but only by the local address, although each message has an associated remote address. (source) .

That way the server can distinguish from which client each message came from. Because the remote address is made up of an ip address and port combination, you should use the same socket throughout your communication of the sever. This is because if you don't, it's possible you could get assigned a different port next time you change the underlying socket.

"If the server looses UDP connectivity with the client, it will ..."

It is possible to loose UPD connectivity eg either of the endpoints in the connection is lost, say I go to the server and pull the plug?

EDIT2: Dan Bryant makes an excellent point in the comments, that links in with what I was saying about.

One thing worth noting is that it's possible for a call to a UDP socket to throw a SocketException with SocketError.ConnectionReset as the error code. UDP does not have any sort of session with structured connect/disconnect, but it does use a dynamically-assigned remote port to allow replies, which is a kind of 'connection'.

After 2 hours trying different -may be random solutions:

  • The server wants you to introduce yourself on a port other than the one you will use to actually send data. "dedicated sockets"

  • You know which IP and Port you are sending start info on, but you do not know which will be used for actual data transmission..

Solution

1- You will create your socket -with known IPEndpoint, and send on it the 'start message'..

2- Then wait to receive from Any IP...

3- The server will response 'welcome message', stating the Endpoint it will use.(by changing parameter ref remoteEP of Socket.ReceiveFrom())

4- You must then change the port you are sending on = remote Endpoint port + 1 (why? standard way or something?)

5- At last you can send and receive normally using these ports

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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