I am writing a loop which will listen on a given port for incoming UDP
packets. If the UDP sender (client), terminates abnormally, then my call to
socket.BeginRec eiveFrom throws a SocketException . I catch this exception,
then re-create the socket, and re-bind it. The next time I call
BeginReceiveFro m, I get that same exception again (" An existing connection
was forcibly closed by the remote host").
When writing a simple loop to listen for UDP packets, what is the right way
to handle this exception? Here's my existing code (the async callback
"DataReceiv ed" is included, too).
Thanks
Greg
public void StartReceiveFro m ()
{
Log (string.Format ("Started UDP Receiver {0} on local port {1}", Name,
localPort));
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType.Dgra m,
ProtocolType.Ud p);
try
{
IPHostEntry localHostEntry = Dns.GetHostByNa me(Dns.GetHostN ame());
IPEndPoint localIpEndPoint = new IPEndPoint(loca lHostEntry.Addr essList[0],
localPort);
socket.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReuseAddress, 1);
socket.Bind(loc alIpEndPoint);
while (true)
{
IPEndPoint remoteIpEndPoin t = new IPEndPoint (IPAddress.Any, 0);
SocketReceiveSt ateObject stateObject = new SocketReceiveSt ateObject ();
stateObject.soc ket = socket;
stateObject.rem oteIPEndpoint = remoteIpEndPoin t;
stateObject.upd Listener = this;
stateObject.nam e = Name;
EndPoint tempRemoteIpEnd Point = (EndPoint)remot eIpEndPoint;
try
{
socket.BeginRec eiveFrom (stateObject.bu f, 0, stateObject.buf .Length,
SocketFlags.Non e, ref tempRemoteIpEnd Point, new AsyncCallback(D ataReceived),
stateObject);
stateObject.don e.WaitOne();
if (stateObject.Da taReceivedExcep tion != null)
{
throw stateObject.Dat aReceivedExcept ion;
}
}
catch (SocketExceptio n ex)
{
// Log (ex.ToString()) ;
try
{
socket.Close ();
}
catch
{
}
Log ("Recreating listening socket in StartReceiveFro m()");
socket = new Socket (AddressFamily. InterNetwork, SocketType.Dgra m,
ProtocolType.Ud p);
socket.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReuseAddress, 1);
socket.Bind(loc alIpEndPoint);
}
}
}
catch (ThreadAbortExc eption)
{
Log (Name + " aborted... closing socket");
socket.Close();
}
}
public void DataReceived (IAsyncResult asyn)
{
SocketReceiveSt ateObject stateObject =
(SocketReceiveS tateObject)asyn .AsyncState;
try
{
EndPoint tempRemoteEndPo int = (EndPoint)state Object.remoteIP Endpoint;
int bytesreceived = stateObject.soc ket.EndReceiveF rom (asyn, ref
tempRemoteEndPo int);
stateObject.rem oteIPEndpoint = (IPEndPoint) tempRemoteEndPo int;
stateObject.upd Listener.OnUdpD ataReceived (new UdpDataReceived EventArgs
(stateObject.bu f, stateObject.rem oteIPEndpoint)) ;
if (AdelaP2PLib.Gl obals.LogEveryU dpSocketReceive )
{
Log (string.Format( "{0} Socket LocalEndPoint {1}, RemoteEndPoint {2}",
stateObject.nam e, stateObject.soc ket.LocalEndPoi nt, tempRemoteEndPo int));
}
}
catch (System.Net.Soc kets.SocketExce ption ex)
{
// Log (ex.ToString()) ;
stateObject.Dat aReceivedExcept ion = ex;
}
catch (ObjectDisposed Exception)
{
Log ("UdpListener.D ataReceived: Socket has been closed (probably due to
listener thread aborting)");
}
finally
{
stateObject.don e.Set();
}
} 0 3378 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Dmitry Akselrod |
last post by:
Hello everyone,
I have a vb.net application that wraps the TCPListener object
in a class. The server connects to the local interface and establishes
itself on port 9900. It then polls for pending connections every 500ms.
I also have a vb6 application that uses the WinSock control at the other end
of the communication tunel. I have to work with vb6 here because it uses
less memory than .NET.
|
by: jack |
last post by:
At this link I have two c# projects, one is a client, the other is a
server. Just point the ip address of the client at the server
http://www.slip-angle.com/hosted/bug/
The server does little more than the examples in the c# documentation
for how to set up an asynchronous server. It just accepts connections,
reads data into a buffer continously, doing nothing with it.
|
by: Laxmikant Rashinkar |
last post by:
Is there any way to use a C# socket in promiscuous mode?
Any sample code that shows how this is done?
any assistance is much appreciated!
thanks
LK
|
by: raza |
last post by:
Hi,
I have been programmin in C# for quite some time now and recently got
into sockets programming in C# though i have done it in C++ on
windows/linux . I have an interesting problem at hand .
I am porting a C++ tunnel library into C# . It has 2 functions
WriteOut: I make a header and send it then send the actual data to the
server and it calls Write function
|
by: Bill English |
last post by:
How do I send an object from one computer to another?
--
I am a 14 year old C# developer, I am completely self taught, so please
don't get mad if I ask a stupid question. Thanks.
| |
by: J C |
last post by:
Hi,
I'm using UDPClient to make a simple DNS server. I notice that
intermittently and unpredictibly I get:
Unhandled Exception: System.Net.Sockets.SocketException: An existing
connection
was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveFrom(Byte buffer, Int32 offset,
Int32 s
|
by: verge |
last post by:
hello everyone!
how's it going? like everyone in here im in need of some help and good
friendship along the way...take a look at this:
//MODIFIED SO IT DEALS WITH WINDOWS FTP USING ACTIVE CONNECTION
//IMPORTANT: the logic is NOT complete, the program works only once and
disconnects or freeze
//One needs to modify or rewrite the program so it is fully functional
for LIST and RETR
|
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...
|
by: J008 |
last post by:
Just looking for some insight as to why the callback "BeginReceiveFromCallback" is not being called in my "Receive" Subroutine below (when I call BeginReceiveFrom). I am trying to read data asynchronously using UDP. I have implemented Send and Connect subroutines in a similar way, and they both seem to work. When I put a breakpoint in the callbacks for Send and Connect, I hit them, and I can see the results I want. However, when I put a...
|
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...
|
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,...
| |
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,...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| | |