473,395 Members | 1,412 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,395 software developers and data experts.

UDP Sockets, receive from

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.BeginReceiveFrom throws a SocketException. I catch this exception,
then re-create the socket, and re-bind it. The next time I call
BeginReceiveFrom, 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
"DataReceived" is included, too).
Thanks

Greg
public void StartReceiveFrom ()
{
Log (string.Format ("Started UDP Receiver {0} on local port {1}", Name,
localPort));
Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
try
{
IPHostEntry localHostEntry = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint localIpEndPoint = new IPEndPoint(localHostEntry.AddressList[0],
localPort);
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
socket.Bind(localIpEndPoint);
while (true)
{
IPEndPoint remoteIpEndPoint = new IPEndPoint (IPAddress.Any, 0);
SocketReceiveStateObject stateObject = new SocketReceiveStateObject ();
stateObject.socket = socket;
stateObject.remoteIPEndpoint = remoteIpEndPoint;
stateObject.updListener = this;
stateObject.name = Name;
EndPoint tempRemoteIpEndPoint = (EndPoint)remoteIpEndPoint;
try
{
socket.BeginReceiveFrom (stateObject.buf, 0, stateObject.buf.Length,
SocketFlags.None, ref tempRemoteIpEndPoint, new AsyncCallback(DataReceived),
stateObject);
stateObject.done.WaitOne();
if (stateObject.DataReceivedException != null)
{
throw stateObject.DataReceivedException;
}
}
catch (SocketException ex)
{
// Log (ex.ToString());
try
{
socket.Close ();
}
catch
{
}
Log ("Recreating listening socket in StartReceiveFrom()");
socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
socket.Bind(localIpEndPoint);
}
}
}
catch (ThreadAbortException)
{
Log (Name + " aborted... closing socket");
socket.Close();
}
}
public void DataReceived (IAsyncResult asyn)
{
SocketReceiveStateObject stateObject =
(SocketReceiveStateObject)asyn.AsyncState;
try
{
EndPoint tempRemoteEndPoint = (EndPoint)stateObject.remoteIPEndpoint;
int bytesreceived = stateObject.socket.EndReceiveFrom (asyn, ref
tempRemoteEndPoint);
stateObject.remoteIPEndpoint = (IPEndPoint) tempRemoteEndPoint;
stateObject.updListener.OnUdpDataReceived (new UdpDataReceivedEventArgs
(stateObject.buf, stateObject.remoteIPEndpoint));
if (AdelaP2PLib.Globals.LogEveryUdpSocketReceive)
{
Log (string.Format("{0} Socket LocalEndPoint {1}, RemoteEndPoint {2}",
stateObject.name, stateObject.socket.LocalEndPoint, tempRemoteEndPoint));
}
}
catch (System.Net.Sockets.SocketException ex)
{
// Log (ex.ToString());
stateObject.DataReceivedException = ex;
}
catch (ObjectDisposedException)
{
Log ("UdpListener.DataReceived: Socket has been closed (probably due to
listener thread aborting)");
}
finally
{
stateObject.done.Set();
}
}
Nov 17 '05 #1
0 3329

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

Similar topics

1
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...
14
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...
6
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
0
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 . ...
7
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.
3
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...
1
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...
5
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...
0
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...
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: 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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
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...
0
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...

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.