How to recover from a WSAECONNRESET (10054)

S

scarleton

I am writing a .NET 2.0 client application uses sockets to communicate
with a firmware on an instrument. The client needs to be able to
recover from a lost connection to the instrument. While trying to send
data to the instrument, after a disconnect/reconnect the socket throws
a exception with the following error: WSAECONNRESET (10054)

The flow is:

1: Open connection
2: send packet
3: receive packet
<Repeat 2 & 3 numerous times>
4: Diconnect
5: Reconnect
6: send
< WSAECONNRESET (10054)> exception!

If the client is closed and restarted, all works well, so I am
confident that the problem can be fixed on the client side, not the
firmware/instrument side of things. Here is some code snippets:

On Connect:
-----------

if (s == null) {
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
}

s.BeginConnect(this.endPoint, new
AsyncCallback(this.AsynchConnectCallback), s);

In AsynchConnectCallback:
-------------------------

Socket s = ar.AsyncState as Socket;
try {
s.EndConnect(ar);
// Setup some threads for reading/writing
}
catch (SocketException se) {
DumpException("AsynchConnectCallback", se);
}

On Disconnect:
 
K

Kevin Spencer

The TCP Reset is (should be) used by a server to prevent old duplicate
connection initiations from causing confusion in TCP's three-way handshake.
(See http://www.rfc-archive.org/getrfc.php?rfc=793). Chances are, this is
caused by trying to re-connect on the same socket (IP Address and Port) as
the previous connection. This might cause the receiver (server) socket to
receive a packet that seems to be out of sequence. This is most probably due
to the sever socket not being closed down immediately after your client
disconnects. Sockets don't disconnect immediately, in order to avoid
sequence issues. They will usually live for the MSL (Maximum Segment
Lifetime) on the server.

You should be able to reconnect after this happens, by closing and then
re-connecting the same socket. Try doing it in a loop, with a short
Thread.Sleep between attempts, and a timeout mechanism to prevent it from
happening indefinitely.
--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
S

Sam Carleton

I found the problem, I was not closing down the connection correctly
when there was an error. Once I did that, I was able to reconnect
cleanly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top