473,738 Members | 10,643 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Raising an exception in a Sockets Async Callback Problem.

Hi,

Ive been trying to work this out for the past 2 days now and im not
getting anywhere fast.

The problem i have is that i am using Asynchronous sockets to create a
Socket Client library. When i try to connect to a server that doesnt
exist it raises a "Connection forcibly rejected by the resmote host"
SocketException .

Because this is thrown inside an Async Callback it is not "bubbling up"
the call stack so the user can handle it so I end up with an
UnhandledExcept ion error.

Because of the nature of the exception message i need to report this so
that the user of the client can handle this themselves (by using a
messagebox or whatever they want to do).

Does anyone know how i can cause this exception to be thrown in the
method that calls BeginInvoke() so i can bubble it back up to the user
to handle themselves in their app?

My code for this block is as follows:
=============== =============== =======

/// <summary>
/// Begins a aynchronous connection operation and delegates a async
/// callback so we don't lock up resources while waiting for the
/// operation to complete.
/// </summary>
public void Connect()
{
if(m_SocketClie nt != null)
{
try
{
m_SocketState = SocketState.Con necting;

// Begin the asynchronous connection to the
// host.

m_SocketClient. BeginConnect(m_ ipEndPoint, new
AsyncCallback(C onnectCallBack) , m_SocketClient) ;
}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;

throw new ClientException ("An error has occured
while trying to connect to the remote host.",
se);
}
}
else
{
m_SocketState = SocketState.Err or;

throw new ClientException ("Cannot open connection when
the socket is uninitiated.");
}
}
----------------------------------------------------------------------
/// <summary>
/// Asynchronous callback for Connect method.
/// </summary>
/// <param name="asyn">Sta tus of the asynchronous operation.</param>
private void ConnectCallBack (IAsyncResult asyn)
{
try
{
// End connection procedure.
m_SocketClient. EndConnect(asyn );

if(m_SocketClie nt.Connected)
{
m_SocketState = SocketState.Con nected;

// Begin receiving data.
ReceiveData();

// Check to see if the event handler exists
if(OnSocketConn ected != null)
{
// Create event args
ClientEventArgs args = new
ClientEventArgs (m_SocketClient );
args.SocketID = m_SocketID;
args.RemoteHost = m_HostAddress;
args.RemoteIP = m_HostIP;
args.RemotePort = m_Port;
args.State = m_SocketState;

// Raise the Connected event.
OnSocketConnect ed(this, args);
}
}
}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;

throw new ClientException ("An Error occured while
attempting to end connection process with remote host.",
se);
}
}

Cheers,

David
Nov 15 '05 #1
3 5133
Why don't you just always save the exception in a variable or so inside your
class that connects.. then the caller class can check for errors afterwards.

Another way you can go is that you may like to fire an event in case there
is some error out there.

"David" <u0***@csc.liv. ac.uk> wrote in message
news:10******** ********@despin a.uk.clara.net. ..
Hi,

Ive been trying to work this out for the past 2 days now and im not
getting anywhere fast.

The problem i have is that i am using Asynchronous sockets to create a
Socket Client library. When i try to connect to a server that doesnt
exist it raises a "Connection forcibly rejected by the resmote host"
SocketException .

Because this is thrown inside an Async Callback it is not "bubbling up"
the call stack so the user can handle it so I end up with an
UnhandledExcept ion error.

Because of the nature of the exception message i need to report this so
that the user of the client can handle this themselves (by using a
messagebox or whatever they want to do).

Does anyone know how i can cause this exception to be thrown in the
method that calls BeginInvoke() so i can bubble it back up to the user
to handle themselves in their app?

My code for this block is as follows:
=============== =============== =======

/// <summary>
/// Begins a aynchronous connection operation and delegates a async
/// callback so we don't lock up resources while waiting for the
/// operation to complete.
/// </summary>
public void Connect()
{
if(m_SocketClie nt != null)
{
try
{
m_SocketState = SocketState.Con necting;

// Begin the asynchronous connection to the
// host.

m_SocketClient. BeginConnect(m_ ipEndPoint, new
AsyncCallback(C onnectCallBack) , m_SocketClient) ;
}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;

throw new ClientException ("An error has occured
while trying to connect to the remote host.",
se);
}
}
else
{
m_SocketState = SocketState.Err or;

throw new ClientException ("Cannot open connection when
the socket is uninitiated.");
}
}
----------------------------------------------------------------------
/// <summary>
/// Asynchronous callback for Connect method.
/// </summary>
/// <param name="asyn">Sta tus of the asynchronous operation.</param>
private void ConnectCallBack (IAsyncResult asyn)
{
try
{
// End connection procedure.
m_SocketClient. EndConnect(asyn );

if(m_SocketClie nt.Connected)
{
m_SocketState = SocketState.Con nected;

// Begin receiving data.
ReceiveData();

// Check to see if the event handler exists
if(OnSocketConn ected != null)
{
// Create event args
ClientEventArgs args = new
ClientEventArgs (m_SocketClient );
args.SocketID = m_SocketID;
args.RemoteHost = m_HostAddress;
args.RemoteIP = m_HostIP;
args.RemotePort = m_Port;
args.State = m_SocketState;

// Raise the Connected event.
OnSocketConnect ed(this, args);
}
}
}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;

throw new ClientException ("An Error occured while
attempting to end connection process with remote host.",
se);
}
}

Cheers,

David

Nov 15 '05 #2
The socket library is going to be a generic one for all the apps i and
other people write so i dont have to keep messing with sockets so
handling it with a variable like that isnt an option as it would involve
manual checking which is a little messy.

Having it fire an event would make it get handled in the wrong place in
the consuming program, i need to be able to catch the exception in a try
/ catch block around the place where the user instantiates a client and
connects.
David

hOSAM wrote:
Why don't you just always save the exception in a variable or so inside your
class that connects.. then the caller class can check for errors afterwards.

Another way you can go is that you may like to fire an event in case there
is some error out there.

"David" <u0***@csc.liv. ac.uk> wrote in message
news:10******** ********@despin a.uk.clara.net. ..
Hi,

Ive been trying to work this out for the past 2 days now and im not
getting anywhere fast.

The problem i have is that i am using Asynchronous sockets to create a
Socket Client library. When i try to connect to a server that doesnt
exist it raises a "Connection forcibly rejected by the resmote host"
SocketExcepti on.

Because this is thrown inside an Async Callback it is not "bubbling up"
the call stack so the user can handle it so I end up with an
UnhandledExce ption error.

Because of the nature of the exception message i need to report this so
that the user of the client can handle this themselves (by using a
messagebox or whatever they want to do).

Does anyone know how i can cause this exception to be thrown in the
method that calls BeginInvoke() so i can bubble it back up to the user
to handle themselves in their app?

My code for this block is as follows:
============= =============== =========

/// <summary>
/// Begins a aynchronous connection operation and delegates a async
/// callback so we don't lock up resources while waiting for the
/// operation to complete.
/// </summary>
public void Connect()
{
if(m_SocketCl ient != null)
{
try
{
m_SocketSta te = SocketState.Con necting;

// Begin the asynchronous connection to the
// host.

m_SocketClien t.BeginConnect( m_ipEndPoint, new
AsyncCallback (ConnectCallBac k), m_SocketClient) ;
}
catch(SocketE xception se)
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("An error has occured
while trying to connect to the remote host.",
se);
}
}
else
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("Cannot open connection when
the socket is uninitiated.");
}
}
----------------------------------------------------------------------
/// <summary>
/// Asynchronous callback for Connect method.
/// </summary>
/// <param name="asyn">Sta tus of the asynchronous operation.</param>
private void ConnectCallBack (IAsyncResult asyn)
{
try
{
// End connection procedure.
m_SocketClien t.EndConnect(as yn);

if(m_SocketCl ient.Connected)
{
m_SocketSta te = SocketState.Con nected;

// Begin receiving data.
ReceiveData() ;

// Check to see if the event handler exists
if(OnSocketCo nnected != null)
{
// Create event args
ClientEventAr gs args = new
ClientEventAr gs(m_SocketClie nt);
args.Socket ID = m_SocketID;
args.RemoteHo st = m_HostAddress;
args.Remote IP = m_HostIP;
args.RemotePo rt = m_Port;
args.State = m_SocketState;

// Raise the Connected event.
OnSocketConne cted(this, args);
}
}
}
catch(SocketE xception se)
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("An Error occured while
attempting to end connection process with remote host.",
se);
}
}

Cheers,

David


Nov 15 '05 #3
You don't have to show all the mess to the user..
It is really that simple as I see it:

I understand that you want to "Block and wait" if there will be any
exceptions on connection operation... because you simply want to throw
exceptions from the function that is seen by the user.

So that means you have to wait *for at least some time* until the
EndConnect() throws the exception that you are after..
something that might smell like this:

// Here it is:
Exception myException = null;
public void Connect(){
if(m_SocketClie nt != null)
{
try
{
m_SocketState = SocketState.Con necting;
// Begin the asynchronous connection to the host.
m_SocketClient. BeginConnect(m_ ipEndPoint, new
AsyncCallback(C onnectCallBack) , m_SocketClient) ;
while( m_SocketState == SocketState.Con necting )
{
System.Threadin g.Thread.Sleep( 10);
}
if ( m_SocketState == SocketState.Err or )
{
throw myException;
}

}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;
throw new ClientException ("An error has occured while trying to connect to
the remote host.", se)
}
}

else
{
m_SocketState = SocketState.Err or;
throw new ClientException ("Cannot open connection when the socket is
uninitiated.") }
}

// <summary>
/// Asynchronous callback for Connect method.
/// </summary>
/// <param name="asyn">Sta tus of the asynchronous operation.</param>
private void ConnectCallBack (IAsyncResult asyn)
{
try
{
// End connection procedure.
m_SocketClient. EndConnect(asyn );
if(m_SocketClie nt.Connected)
{
m_SocketState = SocketState.Con nected;
// Begin receiving data.
ReceiveData();
// Check to see if the event handler exists
if(OnSocketConn ected != null)
{
// Create event args
ClientEventArgs args = new
ClientEventArgs (m_SocketClient );
args.SocketID = m_SocketID;
args.RemoteHost = m_HostAddress;
args.RemoteIP = m_HostIP;
args.RemotePort = m_Port;
args.State = m_SocketState;
// Raise the Connected event.
OnSocketConnect ed(this, args);
}

}

}
catch(SocketExc eption se)
{
m_SocketState = SocketState.Err or;
// keep it with you.
myException = ClientException ("An Error occured while attempting to end
connection process with remote host.", se);
}
}


"David" <u0***@csc.liv. ac.uk> wrote in message
news:10******** ********@dyke.u k.clara.net...
The socket library is going to be a generic one for all the apps i and
other people write so i dont have to keep messing with sockets so
handling it with a variable like that isnt an option as it would involve
manual checking which is a little messy.

Having it fire an event would make it get handled in the wrong place in
the consuming program, i need to be able to catch the exception in a try
/ catch block around the place where the user instantiates a client and
connects.
David

hOSAM wrote:
Why don't you just always save the exception in a variable or so inside your class that connects.. then the caller class can check for errors afterwards.
Another way you can go is that you may like to fire an event in case there is some error out there.

"David" <u0***@csc.liv. ac.uk> wrote in message
news:10******** ********@despin a.uk.clara.net. ..
Hi,

Ive been trying to work this out for the past 2 days now and im not
getting anywhere fast.

The problem i have is that i am using Asynchronous sockets to create a
Socket Client library. When i try to connect to a server that doesnt
exist it raises a "Connection forcibly rejected by the resmote host"
SocketExcepti on.

Because this is thrown inside an Async Callback it is not "bubbling up"
the call stack so the user can handle it so I end up with an
UnhandledExce ption error.

Because of the nature of the exception message i need to report this so
that the user of the client can handle this themselves (by using a
messagebox or whatever they want to do).

Does anyone know how i can cause this exception to be thrown in the
method that calls BeginInvoke() so i can bubble it back up to the user
to handle themselves in their app?

My code for this block is as follows:
============= =============== =========

/// <summary>
/// Begins a aynchronous connection operation and delegates a async
/// callback so we don't lock up resources while waiting for the
/// operation to complete.
/// </summary>
public void Connect()
{
if(m_SocketCl ient != null)
{
try
{
m_SocketSta te = SocketState.Con necting;

// Begin the asynchronous connection to the
// host.

m_SocketClien t.BeginConnect( m_ipEndPoint, new
AsyncCallback (ConnectCallBac k), m_SocketClient) ;
}
catch(SocketE xception se)
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("An error has occured
while trying to connect to the remote host.",
se);
}
}
else
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("Cannot open connection when
the socket is uninitiated.");
}
}
----------------------------------------------------------------------
/// <summary>
/// Asynchronous callback for Connect method.
/// </summary>
/// <param name="asyn">Sta tus of the asynchronous operation.</param>
private void ConnectCallBack (IAsyncResult asyn)
{
try
{
// End connection procedure.
m_SocketClien t.EndConnect(as yn);

if(m_SocketCl ient.Connected)
{
m_SocketSta te = SocketState.Con nected;

// Begin receiving data.
ReceiveData() ;

// Check to see if the event handler exists
if(OnSocketCo nnected != null)
{
// Create event args
ClientEventAr gs args = new
ClientEventAr gs(m_SocketClie nt);
args.Socket ID = m_SocketID;
args.RemoteHo st = m_HostAddress;
args.Remote IP = m_HostIP;
args.RemotePo rt = m_Port;
args.State = m_SocketState;

// Raise the Connected event.
OnSocketConne cted(this, args);
}
}
}
catch(SocketE xception se)
{
m_SocketSta te = SocketState.Err or;

throw new ClientException ("An Error occured while
attempting to end connection process with remote host.",
se);
}
}

Cheers,

David


Nov 15 '05 #4

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

Similar topics

3
2821
by: Corne Oosthuizen | last post by:
I'm writing a Telnet Server application using Asynchronous sockets. I spawn a listener thread to handel incomming connections and create a separate client socket for each new connection. I then set the new client socket to BeginReceive(). My problem: When two client socket connections send data
1
3436
by: Barry Anderberg | last post by:
I am using asynch sockets and so I call BeginReceive and then in my callback function I have certain events that would cause me to want to throw an exception. The problem of course is that the callback function is executing in a separate thread from the main thread so when I throw the exception it's apparently impossible to handle it in the calling thread (ie the thread that called BeginReceive(..). Is there a way to throw an...
3
2530
by: User N | last post by:
I'm working on a proxy which must support at least a dozen simultaneous connections from local clients to remote servers. It is conceivable that someone might want to run it in non-local mode, with as many as 3-4 dozen simultaneous connections from remote clients to remote servers. Supporting that is desireable but optional. The proxy will have to maintain client/server connections for up to several hours, but the traffic will be...
11
2408
by: Steven | last post by:
Hi, I need to write an application using sockets. I have a server and about 10 clients "speaking" at the same time with the server, so i guess i need to use asynchronous sockets. But the server will receive from the clients an ascii string with a viariable length. And in all the example i found, the size of the buffer is always fixed (private byte theBuffer = new byte). I probably misunderstood the use of the buffer !
2
7126
by: jasonsgeiger | last post by:
From: "Factor" <jasonsgeiger@gmail.com> Newsgroups: microsoft.public.in.csharp Subject: Multiple Clients, One port Date: Wed, 19 Apr 2006 09:36:02 -0700 I'm been working with sockets for a short while now using a server program a former coworker started. The program listens on a port for incomming connections. When a valid connection is made (we send this init string into the socket from the clients) the server closes the socket so...
5
2250
by: Dan Ritchie | last post by:
I've got a client/server app that I used to send large amounts of data via UDP to the client. We use it in various scenarios, one of which includes rendering a media file on the client as it is transferred via the underlying UDP transport. In this scenario it is very important to keep CPU usage as low as possible. Both the client and server were originally written in C++, but I've re-written the client in C#, partly to simplify it, but...
0
1625
by: Raymondr | last post by:
Hi, First a brief description of out application: We have a webapplication which calls a couple of webservices during one request (postback). These calls to the webservices are made concurrent using asynchronous webservices calls. The number of webservices called concurrent is between 1 and 18. The webservice calls are made using SSL with a X509 clientcertificate. The application is underhigh load
6
1652
by: Richard | last post by:
Hi All, I don't know in which group my question needs to be posted so here i go: I know that the socket 'begin...' methods uses the threadpool to call the callback function but does that mean that the sockets can't handle more than 25 concurrent 'begin...' methods that complete since the threadpool only has 25 threads to process the completion? Thanks for any insight in this.
2
4082
by: koredump | last post by:
Hi all, I have a windows app that makes some asyc calls to my webservice (WSE 3.0 with MTOM). exception gets thrown in the client win app. This exception is being thrown on another thread by a class in the System.Web.Services namespace and I have not been able to catch it and dispose of it. I've tried placing try/catch blocks in several places in my code, but this exception doesn't seem to bubble up the stack.
0
8969
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9335
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...
0
9208
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...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6751
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
4570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.