6

Let's assume I have an UDP socket that was open on a certain address / port and then hanged. When I try to initialize a new UDP Socket (UDPClient) on that same address / port of course it raises a SocketException since it finds that is already in use.

Is it possible to kill from code the hanged socket so I can reuse it?

EDIT: Here's the code causing the UDP to stay blocked (Apparently) Gracefully Closed UDPClient leaves the socket blocked

Community
  • 1
  • 1
Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
  • 1
    Not that I'm aware of. Traditionally, if this might happen, you should set a timeout on the connection. Alternatively, there are potential problems with doing it consistently if the old socket recovers, but you can call `.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true)` before connecting with a new socket. – John C May 09 '14 at 11:16
  • 1
    Have you tried closing it? – 500 - Internal Server Error May 09 '14 at 11:20
  • You could set some 'terminate' flag and then send the port a datagram yourself to make the blocking readFrom(), or whatever, return. – Martin James May 09 '14 at 11:40
  • @500-InternalServerError I tried doing it ( as posted here: http://stackoverflow.com/questions/23564939/apparently-gracefully-closed-udpclient-leaves-the-socket-blocked ) but despite apparently closing it in a graceful way, the socket stays blocked. – Saverio Terracciano May 09 '14 at 12:42
  • @MartinJames I can't handle it because I only read from the Socket, I am unable to do any change to the server – Saverio Terracciano May 09 '14 at 12:42
  • 1
    @SaverioTerracciano - it's UDP - you can send a datagram directly to yourself, no problem. – Martin James May 09 '14 at 14:22
  • @MartinJames I know it's UDP and theorically could send myself a datagram but: The server is a code I can't change since I have no source, as for the client it supposedly closes gracefully (check the EDIT link provided in the question) but if I try to reconnect to the same socket, it won't. – Saverio Terracciano May 11 '14 at 16:59

1 Answers1

0

You can set the ReuseAddress socket option in the socket so that it allows to listen on the same IP & port on a different socket.

dvasanth
  • 1,337
  • 1
  • 9
  • 10