About C# UDP Sockets

↘锁芯ラ 提交于 2020-01-04 01:05:08

问题


  • 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


回答1:


"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 e.g. 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'.




回答2:


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



来源:https://stackoverflow.com/questions/2757868/about-c-sharp-udp-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!