473,385 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Detecting Remote Client Socket Close in BeginReceive

In the following code snippet, the thread successfully makes it to the
line where it waits for data to be received. Then the client closes the
connection. The thread wakes up and returns from the WaitOne()
operation. No exception is thrown when it loops and executes
BeginReceive() again. The WaitOne() operation returns immediately.
Thus, there's an endless loop.

How does one detect that the remote client has closed the connection in
this situation?
//
// Started as a new thread to handle data received on an
// open socket.
//
private void ReceiveDataEventLoop(Socket clientSocket) {
while (true) {
try {
ClientState clientState = new ClientState(clientSocket);
IAsyncResult result = clientSocket.BeginReceive(
clientState.Buffer,
0,
clientState.Buffer.Length,
SocketFlags.None,
new AsyncCallback(this.ReceiveDataCallback),
clientState);

// Wait for the EndReceive before issuing a new BeginReceive
// When the remote client closes the connection, this starts
// to return immediately. How to identify that remote client
// closed connection?
result.AsyncWaitHandle.WaitOne();

} catch (SocketException) {
removeSocket(clientSocket);
break;
} catch (Exception) {
removeSocket(clientSocket);
break;
}
}
}

Oct 26 '06 #1
2 6478
OK. I have a workaround:

Instead of using "result.AsyncWaitHandle.WaitOne()", I created a
ManualResetEvent and passed it to the BeginReceive delegate. When the
BeginReceive delegate starts, it gets the number of bytes when it calls
EndReceive. If 0, the BeginReceive delegate closes the socket. After
processing the data, the ManualResetEvent is set. Thus, when the
ReceiveDataEventLoop wakes up, it will try to access a disposed object
when it calls BeginReceive and then exit from its event loop.

O.B. wrote:
In the following code snippet, the thread successfully makes it to the
line where it waits for data to be received. Then the client closes the
connection. The thread wakes up and returns from the WaitOne()
operation. No exception is thrown when it loops and executes
BeginReceive() again. The WaitOne() operation returns immediately.
Thus, there's an endless loop.

How does one detect that the remote client has closed the connection in
this situation?
//
// Started as a new thread to handle data received on an
// open socket.
//
private void ReceiveDataEventLoop(Socket clientSocket) {
while (true) {
try {
ClientState clientState = new ClientState(clientSocket);
IAsyncResult result = clientSocket.BeginReceive(
clientState.Buffer,
0,
clientState.Buffer.Length,
SocketFlags.None,
new AsyncCallback(this.ReceiveDataCallback),
clientState);

// Wait for the EndReceive before issuing a new BeginReceive
// When the remote client closes the connection, this starts
// to return immediately. How to identify that remote client
// closed connection?
result.AsyncWaitHandle.WaitOne();

} catch (SocketException) {
removeSocket(clientSocket);
break;
} catch (Exception) {
removeSocket(clientSocket);
break;
}
}
}
Oct 26 '06 #2
"O.B." <fu******@bellsouth.netwrote in message
news:12*************@corp.supernews.com...
[...]
How does one detect that the remote client has closed the connection in
this situation?
As you have found, the receive function returns a bytes received value of 0
when the connection is closed.

However, your problem has less to do with that, than that you have created
an infinite loop that tries to receive over and over again without any means
of checking the socket for validity.

It seems to me that if you insist on this design, then the BeginReceive
method *ought* to throw an exception once your socket has been closed. That
is, after receiving 0 for the return value for EndReceive, you ought to be
able to just close the socket there, causing an exception here and allowing
the loop to exit.

However, in that case you don't have a direct means of knowing whether the
connection was closed normally or abnormally. IMHO, it would be better to
not have this design in the first place, requeuing the receive *only* when
you know you have successfully completed the previous receive (that is, in
the same code where you call EndReceive).

Pete
Oct 26 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Tim Gosselin | last post by:
I am writing a tcp tunnel but cannot find a way of detecting when a socket shuts down its read end without writing to the socket. For testing the write end of the remote endpoint I just do a: if...
3
by: James Yang | last post by:
Hi, I am using Sockets to connect to a remote computer and send data using Socket.Send() and receive using Socket.Receive() (block mode) . for somereason tho, when the client disconnects the...
3
by: Adam Clauss | last post by:
There seems to be various methods to determine when the remote client disconnects, but all of them I have seen are Synchronous. AKA: Right before you try to send or receive data, check. Is there...
4
by: Brian Rice | last post by:
I have a socket application that is sending and receiving packets asynchronously. It works great except, when I receive packets that are larger than my receive buffer which then generate several...
6
by: Bruce Vander Werf | last post by:
I am using the asynchronous send/receive methods of the Socket class. When the remote end closes the socket, the callback for receive is called and EndReceive returns 0. Socket.Connected still...
4
by: =?Utf-8?B?U2hhdW5P?= | last post by:
Hi, I set up an client to asynchronously receive data from it's connection. When i'm finished, i close the client using try {...
9
by: timor.super | last post by:
Hi group, I've written a client/server application, using the dotnet sockets. In my server, I have a thread waiting for messages with : ret = currSocket.Receive(buffer, 1024,...
3
by: Jason | last post by:
I am working on an asynchronous UDP socket server platform, and I am running into what appears to be a common problem but I have not found a good answer yet. If this was TCP, when the routine...
5
by: tichi | last post by:
I'm writing a program that in its most simplest form acts as a proxy between a local client and a remote server. But I cannot figure out how to detect when either the connection to the client is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.