473,842 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Closing socket during async Receive

I am trying to write a Tcp "Server" that opens a class that wraps a tcp
socket when a new connection is made (Listener.Accep tSocket()).
Everything is going swimmingly except when I try to close the socket
during a read and I get the following error:

<error_msg>
An unhandled exception of type 'System.Net.Soc kets.SocketExce ption'
occurred in system.dll

Additional information: The I/O operation has been aborted because of
either a thread exit or an application request
</error_msg>

The following is the delegate function for the BeginReceive call:

private void ReadStream(IAsy ncResult ar)
{
if(IsAvailable)
{
lock(_socClient ) //*** - Futile attempt to stop the exception
{

int intByteCount = _socClient.EndR eceive(ar);//**** - THIS
IS WHERE I GET MY EXCEPTION

if(intByteCount > 0)
{
_tmrTimeout.Sto p();

ProcessInput(_a bytBuffer, intByteCount);//Adds any
ASCII text to a string buffer

if(IsAvailable)
{
_socClient.Begi nReceive(_abytB uffer,0,
BUFFER_LENGTH,S ocketFlags.None ,
_acbBeginReadCa llback,_socClie nt);
}
_tmrTimeout.Sta rt();
}
else
{
Close(true);
}
}
}
else
{
Close(false);
}
}
My shut down routine looks like this:

public bool IsAvailable
{
get
{
if((!_bShutdown ) && (_socClient != null) &&
_socClient.Conn ected)
{
return true;
}
else
{
return false;
}
}
}

public void Close(bool bSendStatusUpda te)
{
if(IsAvailable)
{
lock(_socClient )
{
_bShutdown = true; //An attempt to indicate what is going
on... SO didn't work

_socClient.Shut down(SocketShut down.Both);
_socClient.Clos e();
}
//_socClient = null;
}
_tmrTimeout.Sto p();

if(bSendStatusU pdate)
{
OnClientStatusC hanged(new ClientStatusCha ngedEventArgs(
CommStatusType. CLOSED,RemoteEn dPoint,"Closed" ));
}
}

#region IDisposable Members

public void Dispose()
{
if(IsAvailable)
{
Close(false);
}
}

#endregion

I thought that maybe I can manually call the EndReceive function from
the Close() routine but I cannot declare a IAsyncResult object. Any
suggestions to close the connection would be great.

Once again, thank you to the Google community for saving my behind.
I'll try to answer a couple of other messages in return.

Cheers,

Russ

Jun 19 '06 #1
8 11027
"Dinsdale" <ru********@gma il.com> wrote:
I am trying to write a Tcp "Server" that opens a class that wraps a tcp
socket when a new connection is made (Listener.Accep tSocket()).
Everything is going swimmingly except when I try to close the socket
during a read and I get the following error:

<error_msg>
An unhandled exception of type 'System.Net.Soc kets.SocketExce ption'
occurred in system.dll

Additional information: The I/O operation has been aborted because of
either a thread exit or an application request
</error_msg> [snip] int intByteCount = _socClient.EndR eceive(ar);//**** - THIS
IS WHERE I GET MY EXCEPTION [snip] I thought that maybe I can manually call the EndReceive function from
the Close() routine but I cannot declare a IAsyncResult object. Any
suggestions to close the connection would be great.
From my somewhat limited experience with async sockets, there are two
things interacting here. First, interrupting a blocking call like
Receive (if you weren't using async sockets) from another thread would
result in an exception being thrown - that just happens to be how the
..NET Socket class communicates the interruption at the Winsock level.

The second thing is that exceptions thrown from an asynchronous
operation get delayed until the call to the End* method. So, you only
get notification of the interruption when you call EndReceive().

Basically, what you're seeing is normal behaviour, AFAIK. You've got to
be prepared to catch the exception thrown when and where you call
EndReceive().
Once again, thank you to the Google community for saving my behind.
I'll try to answer a couple of other messages in return.


Believe it or not, this is the Microsoft community :) These newsgroups
are hosted on Microsoft's servers (NNTP on news.microsoft. com), and get
mirrored to Usenet. Google Groups is a web-based interface to Usenet (as
well as having its own, non-Usenet, groups).

-- Barry

--
http://barrkel.blogspot.com/
Jun 19 '06 #2
> Believe it or not, this is the Microsoft community :) These newsgroups
are hosted on Microsoft's servers (NNTP on news.microsoft. com), and get
mirrored to Usenet.
Nooooooo! Well, okay, thank you to the evil empire and it's minions of
darkness (of which I myself am a sergeant). ;)
Basically, what you're seeing is normal behaviour, AFAIK. You've got to
be prepared to catch the exception thrown when and where you call
EndReceive(). So if I understand this correctly, there will be an exception -
REGARDLESS of what I do - when I close the socket and there was a
BeginReceive call made. I find this odd and frustrating, but I guess it
is consistent with other async. functionality (i.e. when you stop a
thread). I just don't like to write code that is EXPECTED to use an
exception block. This is normal behaviour, not an 'exception' to the
regular functioning of a control (IMHO).

Thanks for the help Barry!

Russ
Barry Kelly wrote: "Dinsdale" <ru********@gma il.com> wrote:
I am trying to write a Tcp "Server" that opens a class that wraps a tcp
socket when a new connection is made (Listener.Accep tSocket()).
Everything is going swimmingly except when I try to close the socket
during a read and I get the following error:

<error_msg>
An unhandled exception of type 'System.Net.Soc kets.SocketExce ption'
occurred in system.dll

Additional information: The I/O operation has been aborted because of
either a thread exit or an application request
</error_msg>

[snip]
int intByteCount = _socClient.EndR eceive(ar);//**** - THIS
IS WHERE I GET MY EXCEPTION

[snip]
I thought that maybe I can manually call the EndReceive function from
the Close() routine but I cannot declare a IAsyncResult object. Any
suggestions to close the connection would be great.


From my somewhat limited experience with async sockets, there are two
things interacting here. First, interrupting a blocking call like
Receive (if you weren't using async sockets) from another thread would
result in an exception being thrown - that just happens to be how the
.NET Socket class communicates the interruption at the Winsock level.

The second thing is that exceptions thrown from an asynchronous
operation get delayed until the call to the End* method. So, you only
get notification of the interruption when you call EndReceive().

Basically, what you're seeing is normal behaviour, AFAIK. You've got to
be prepared to catch the exception thrown when and where you call
EndReceive().
Once again, thank you to the Google community for saving my behind.
I'll try to answer a couple of other messages in return.


Believe it or not, this is the Microsoft community :) These newsgroups
are hosted on Microsoft's servers (NNTP on news.microsoft. com), and get
mirrored to Usenet. Google Groups is a web-based interface to Usenet (as
well as having its own, non-Usenet, groups).

-- Barry

--
http://barrkel.blogspot.com/


Jun 19 '06 #3
On 19 Jun 2006 09:56:57 -0700, Dinsdale wrote:
Once again, thank you to the Google community for saving my behind.
I'll try to answer a couple of other messages in return.


Barry already gave you a good answer. What you're seeing is the normal
behaviour and this exception allows you to know that the socket has been
closed and that you should give up trying to do any further processing.

I just wanted to point out, since you're obvioulsy new to usenet, that this
is not the Google community here but, as Barry pointed out, the usenet
community. There are many web sites that allow you to access usenet
newsgroups from your web browser and Google is just one of them. I suggest
that you get yourself a usenet newsgroup reader software such as Outlook
Express, 40tude Dialog, Forte Agent, etc and use it to read and post on
usenet instead of using Google. It's a lot easier to follow a conversation,
post and browse a newsgroup using a specialized software rather than using
Google's web interface. And you'll quickly find yourself hooked to usenet
and start reading and posting on your favorite newsgroups everyday, which
will allow you to not feel guilty of always asking questions without
contributing (note though that people asking questions here are absolutely
not expected to contribute in return although it's always a good thing when
the community grows).
Jun 19 '06 #4
"Dinsdale" <ru********@gma il.com> wrote:
So if I understand this correctly, there will be an exception -
REGARDLESS of what I do - when I close the socket and there was a
BeginReceive call made. I find this odd and frustrating, but I guess it
is consistent with other async. functionality (i.e. when you stop a
thread). I just don't like to write code that is EXPECTED to use an
exception block. This is normal behaviour, not an 'exception' to the
regular functioning of a control (IMHO).


The proper way to close the connection is to call Shutdown() on the
other thread, not Close(). That way you get the standard close condition
for the connection (i.e. a read of 0 bytes). For example:

---8<---
using System;
using System.Threadin g;
using System.Net.Sock ets;
using System.Net;

class App
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPA ddress.Loopback , 2000);
server.Start();
try
{
Console.WriteLi ne("Listening on {0}", server.LocalEnd point);
using (Socket client = server.AcceptSo cket())
{
Console.WriteLi ne("Accepted: {0}",
client.RemoteEn dPoint);

ThreadPool.Queu eUserWorkItem(d elegate
{
Console.WriteLi ne("Going to close in 1 second.");
Thread.Sleep(Ti meSpan.FromSeco nds(1));
Console.WriteLi ne("Closing..." );
client.Shutdown (SocketShutdown .Both);
});

byte[] buffer = new byte[512];
int read = client.Receive( buffer);
Console.WriteLi ne("Read {0} bytes.", read);
}
}
finally
{
server.Stop();
}
}
}
--->8---

-- Barry

--
http://barrkel.blogspot.com/
Jun 19 '06 #5
>What you're seeing is the normal
behaviour and this exception allows you to know that the socket has been
closed and that you should give up trying to do any further processing.
After re-reading the documentation, I see your point. when EndReceive
returns 0 bytes, it's a REMOTE host disconnect. I expected the same
behaviour on local endpoint disconnects.

Thank you for clarifying the usenet thing (Barry and Mehdi). I will be
sure to look into other usenet clients.

Cheers,
Russ

Mehdi wrote: On 19 Jun 2006 09:56:57 -0700, Dinsdale wrote:
Once again, thank you to the Google community for saving my behind.
I'll try to answer a couple of other messages in return.


Barry already gave you a good answer. What you're seeing is the normal
behaviour and this exception allows you to know that the socket has been
closed and that you should give up trying to do any further processing.

I just wanted to point out, since you're obvioulsy new to usenet, that this
is not the Google community here but, as Barry pointed out, the usenet
community. There are many web sites that allow you to access usenet
newsgroups from your web browser and Google is just one of them. I suggest
that you get yourself a usenet newsgroup reader software such as Outlook
Express, 40tude Dialog, Forte Agent, etc and use it to read and post on
usenet instead of using Google. It's a lot easier to follow a conversation,
post and browse a newsgroup using a specialized software rather than using
Google's web interface. And you'll quickly find yourself hooked to usenet
and start reading and posting on your favorite newsgroups everyday, which
will allow you to not feel guilty of always asking questions without
contributing (note though that people asking questions here are absolutely
not expected to contribute in return although it's always a good thing when
the community grows).


Jun 19 '06 #6
"Dinsdale" <ru********@gma il.com> wrote:
What you're seeing is the normal
behaviour and this exception allows you to know that the socket has been
closed and that you should give up trying to do any further processing.


After re-reading the documentation, I see your point. when EndReceive
returns 0 bytes, it's a REMOTE host disconnect. I expected the same
behaviour on local endpoint disconnects.


Calling Shutdown() instead of Close() will also cause EndReceive to
return 0 bytes, for a LOCAL host disconnect. Ideally, you should call
Close() on the thread that logically "owns" the underlying socket.

-- Barry

--
http://barrkel.blogspot.com/
Jun 19 '06 #7
I call both Shutdown() and Close():

if(IsAvailable)
{
lock(_socClient )
{
_bShutdown = true;
_socClient.Shut down(SocketShut down.Both);
_socClient.Clos e();
}
}

Is the call to close unnecessary?

Russ
Barry Kelly wrote:
"Dinsdale" <ru********@gma il.com> wrote:
What you're seeing is the normal
behaviour and this exception allows you to know that the socket has been
closed and that you should give up trying to do any further processing.


After re-reading the documentation, I see your point. when EndReceive
returns 0 bytes, it's a REMOTE host disconnect. I expected the same
behaviour on local endpoint disconnects.


Calling Shutdown() instead of Close() will also cause EndReceive to
return 0 bytes, for a LOCAL host disconnect. Ideally, you should call
Close() on the thread that logically "owns" the underlying socket.

-- Barry

--
http://barrkel.blogspot.com/


Jun 23 '06 #8
Ideally, you should call
Close() on the thread that logically "owns" the underlying socket.

I have moved the Close() call into the delegate function that handles
the BeginReceive calls and that eliminated the exception. The Close()
function is only called after the EndReceive() call returns 0 bytes,
instead of me forcing it immediately aftger the shutdown call.

if(intByteCount > 0)
{
//...Normal Processing
}
Else
{
Close(true);
_socClient.Clos e();
}

Thanks for your help Barry, I was POSITIVE that there was a way to do
this without having to rely on an exception.

Russ

Dinsdale wrote: I call both Shutdown() and Close():

if(IsAvailable)
{
lock(_socClient )
{
_bShutdown = true;
_socClient.Shut down(SocketShut down.Both);
_socClient.Clos e();
}
}

Is the call to close unnecessary?

Russ
Barry Kelly wrote:
"Dinsdale" <ru********@gma il.com> wrote:
>What you're seeing is the normal
> behaviour and this exception allows you to know that the socket has been
> closed and that you should give up trying to do any further processing.

After re-reading the documentation, I see your point. when EndReceive
returns 0 bytes, it's a REMOTE host disconnect. I expected the same
behaviour on local endpoint disconnects.


Calling Shutdown() instead of Close() will also cause EndReceive to
return 0 bytes, for a LOCAL host disconnect. Ideally, you should call
Close() on the thread that logically "owns" the underlying socket.

-- Barry

--
http://barrkel.blogspot.com/


Jun 23 '06 #9

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

Similar topics

4
2434
by: flupke | last post by:
Hi, I have a gui (made in wxPython) that enables a user to connect to a server and issue some commands. The problem occurs when i try to disconnect the client. It exits but it doesn't return to the prompt. I have to push Ctrl-C in order to have it exit completely. The GUI is closed though. This is a piece of code from the main class that connects to the server and starts a thread that handles the connection: =======================...
2
9238
by: dream machine | last post by:
Hi all , with BegeinReceive I can build async method of Socket Class that Receive the data from the Socket Client . My question is , if I have this code that create 3 Receive Async Call : <code> mySocket.BeginReceive(param1,param2,param3.....); mySocket.BeginReceive(param1,param2,param3......); mySocket.BeginReceive(param1,param2,param3......);
3
3713
by: Robert A. van Ginkel | last post by:
In news:OZ0W9RsdDHA.2432@TK2MSFTNGP10.phx.gbl... I ask the question how I can see if all the data is on the other side of the connection. I got as answer that I should use the blocking property. I tried this I don't see any diffents, I am sending 10Mb and the Send/BeginSend command doesn't wait till the data is on the remotepoint. Can somebody pls. explain this. Regards Robert.
6
4132
by: roger beniot | last post by:
I have a program that launches multiple threads with a ThreadStart method like the following (using System.Net.Sockets.Socket for UDP packet transfers to a server): ThreadStart pseudo code: Connect Receive response Send Connect ACK
5
3693
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose but have been unsuccessful in finding the answers so far. Either because my understanding of sockets isn't where it needs to be or my questions are too basic. My programming environment is Windows XP, Visual Studio .NET 2003 and C#. So here it...
7
9709
by: Ole | last post by:
Hi, I'm going to develop a socket communication between an instrument (running CE 5.0 with Compact Fraework V2) and a PC. As the instrument should only connect to one PC at a time I believe that the sync version of the socket should be the easiest - or what??? (please tell if I'm wrong). Are there anyone who is able to point to a Server and Client example code in C# VS2005 (I've only been able to find a C++ version) ???
4
3610
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket client and asynchronous socket server example code provided in the .NET framework developers guide is a great start but I have not dealt with sockets before and I am struggling with something. From what I can tell the sample server code ...
5
1831
by: Navin Mishra | last post by:
Hi, In load test of our .NET 2.0 socket application on Win2003 server, we are seeing sometimes WSEWOULDBLOCK error when sending data to clients. We are using synchronoous scokets with SendTimout of 2 secs. Is it normal ? Thanks in advance and regards Navin
10
8074
by: ColoradoGeiger | last post by:
I have a fairly standard server application that I am using asynchronous socket calls to make connections, send and receive data, and all of that jazz. No blocking methods was my goal in writing this and it's gone very well so far. But coming from the blocking world, I want to have some timeouts on my receive routines and I after reading a lot on MSDN and here, I get the impression that once I set one of these Begin... methods a running...
0
9715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10944
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10610
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10672
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10313
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7855
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5884
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4499
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4089
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.