473,320 Members | 2,177 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,320 software developers and data experts.

UDP broadcasting problem

Hi,

I have this problem in my UDP broadcasting, im a newbie in UDP,
any help at all would be very much appreciated. I have a working UDP
broadcast that sends and recieves without any problem. I tried sending a
message 30 times in a loop simultaneously and i recieved all of them without
any problem. But last night i tried sending 64kb message in the same loop for
30 times and all i recieved was 5 messages out of 30, im not sure if i missed
the other 25 messages or most of the messages sent were not finished.

So i tried, placing a thread.sleep(500) every before it sends a
message and everything worked out fine again, i recieved all the messages
without any problem. The problem now is that i cannot risk having a
thread.sleep(500) around as it would affect the whole system. Is there
anything i can do to recieve them completely without having to use sleep?

Can anyone suggest on something? Sample code would really really help
but anything you can suggest is good enough, i just desperately need this
one... Thank you so much in advance!!!

Aug 26 '06 #1
4 2499
"Rain" <Ra**@discussions.microsoft.comwrote
But last night i tried sending 64kb message in the same loop for
30 times and all i recieved was 5 messages out of 30, im not sure
if i missed the other 25 messages or most of the messages sent
were not finished.
I would wager that the other 25 udp packets came in, but your code missed
them. In general, it's very rare to "lose" a UDP packets - especially if
you're on a LAN, or using the loopback address on your computerer.
Depening on the scalability of what you're doing, you're going to want to
either:
1 - (low scalability requirements, easier coding) create a UDP Listen thread
for each socket you're listening on and receive data that way.
2 - (high scalability, often confusing to newcomers) Use the Begin/End
methods on the sockets and do asynchronous programming. This scales very
well, is incredibly reliable, and (once you get the hang of it) is pretty
easy. The MS primers can be found at:
http://msdn2.microsoft.com/en-us/library/ms228969.aspx
--
Chris Mullins MCSD.Net, MCPD:Enterprise
http://www.coversant.net/blogs/cmullins
Aug 26 '06 #2
Hi Chris,

Im already doing the number one, low scalability, on the UDP im
doing that doesnt receive or process the entire messages. Since im still a
newbie here i cant really get the idea on the number 2.. Would you care to
explain? If its okay with you that is.. Begin/End are methods of Socket
right? Im not using any socket, both my receiving and seding is using
UDPClient. Thank You so much!

"Chris Mullins" wrote:
"Rain" <Ra**@discussions.microsoft.comwrote
But last night i tried sending 64kb message in the same loop for
30 times and all i recieved was 5 messages out of 30, im not sure
if i missed the other 25 messages or most of the messages sent
were not finished.

I would wager that the other 25 udp packets came in, but your code missed
them. In general, it's very rare to "lose" a UDP packets - especially if
you're on a LAN, or using the loopback address on your computerer.
Depening on the scalability of what you're doing, you're going to want to
either:
1 - (low scalability requirements, easier coding) create a UDP Listen thread
for each socket you're listening on and receive data that way.
2 - (high scalability, often confusing to newcomers) Use the Begin/End
methods on the sockets and do asynchronous programming. This scales very
well, is incredibly reliable, and (once you get the hang of it) is pretty
easy. The MS primers can be found at:
http://msdn2.microsoft.com/en-us/library/ms228969.aspx
--
Chris Mullins MCSD.Net, MCPD:Enterprise
http://www.coversant.net/blogs/cmullins
Aug 27 '06 #3
-------------My OnConnect and OnReceive Events Mthods-----------------

private void Client_OnConnect( string msg )
{
FileLogger Log = FileLogger.New;
Log.AppendToLogFile("Connected.");
Console.WriteLine( "Connected.");
}
private void Client_OnRecieve( string msg )
{

FileLogger Log = FileLogger.New;
Log.AppendToLogFile( msg );
Console.WriteLine(msg);
}

--------------My Multicasting code:-------------------------------

namespace DigiSoft.Multicasting
{
/// <summary>
/// Summary description for Multicasting.
/// </summary>
///
public delegate void OnRecieveDataEventHandler( string Message );
public delegate void OnConnectEventHandler(string Message );
public delegate void OnDisconnectEventHandler( string Message );
public delegate void OnErrorEventHandler( string errorMsg );

public class Multicasting
{
//Properties
public string MulticastGroup
{
get { return mygroupAddress; }
set { mygroupAddress = value; }
}

public int groupPort
{
get { return mygroupPort; }
set { mygroupPort = value; }
}

public int TTL
{
get { return myTTL; }
set { myTTL = value; }
}
private UdpClient thisClient;
private IPEndPoint RemoteEndPoint;
private string mygroupAddress;
private int mygroupPort;
private int myTTL;
private bool done;
private bool isRunning = false;

public void Start()
{
try
{
UdpClient udp = AsyncState as UdpClient;
thisClient= new UdpClient( mygroupPort );
thisClient.JoinMulticastGroup( IPAddress.Parse(mygroupAddress), myTTL );
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(mygroupAddress),
mygroupPort);

Thread myThread = new Thread( new ThreadStart( this.Listen ));
#if !CF
myThread.IsBackground = true;
#endif
myThread.Start();
isRunning = true;
if ( OnConnect != null)
OnConnect(string.Empty );

//send whereabouts to the group
byte[] bs = System.Text.Encoding.UTF8.GetBytes( Dns.GetHostByName(
Dns.GetHostName()).AddressList[0].ToString() + " has joined." ) ;
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);

}
catch(Exception e)
{
//Some error Message;
if(OnError!=null)
OnError("Error Connecting : " + e.Message);
done = true;
isRunning = false;
}
}

private void Listen()
{
done = false;
while(!done)
{

try
{
#if !CF
IPEndPoint IPEndPointNull = null;
#else

IPEndPoint IPEndPointNull = new IPEndPoint( IPAddress.Any,
this.mygroupPort );
#endif
byte[] bs = thisClient.Receive( ref IPEndPointNull);
string msg = System.Text.Encoding.UTF8.GetString(bs,0,bs.Length );

if ( OnRecieve != null )
OnRecieve(msg);
}
catch(Exception e)
{
//Some Error Message
if(OnError!=null)
OnError("Error Recieving: " + e.Message);
done = true;
isRunning = false;

}
}
}

public void Stop()
{

if ( !isRunning ) return ;

//Say your goodbyes to all the members of the group...
done = true;
isRunning = false;

byte[] bs = System.Text.Encoding.UTF8.GetBytes( Dns.GetHostByName(
Dns.GetHostName() ).AddressList[0].ToString() + " has left." ) ;
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);

#if CF
Thread.Sleep(300);
#endif

if( OnDisconnect!=null)
OnDisconnect( string.Empty );
try
{
thisClient.DropMulticastGroup(IPAddress.Parse(mygr oupAddress));
thisClient.Close();
}
catch(Exception e)
{
if(OnError!=null)
OnError("Error Closing: " + e.Message);
}
}

public void Send( string Message)
{
if ( !isRunning ) return ;

try
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(Message);
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);
}
catch(Exception e)
{
//Some Error Message
if(OnError!=null)
OnError("Error Sending: " + e.Message);
done = true;
isRunning = false;
}
}
public event OnRecieveDataEventHandler OnRecieve;
public event OnConnectEventHandler OnConnect;
public event OnDisconnectEventHandler OnDisconnect;
public event OnErrorEventHandler OnError;
}
}
Aug 27 '06 #4
UDP is not guaranteed to be delivered. Your program has to be there and
ready to receive when the next packet comes. In your code you are
writing the message to a logger and the console. These are very slow
operations that take milliseconds. During this time the UDP client
software can't be looking for new messages coming in. What you need to
do is have your Client_OnRecieve methods quickly post your message to a
queue and leave so it can get back to looking for new messages. Then
have a background thread that de-queues messages and processes them.

Hope that helps
Leon Lambert

Rain wrote:
-------------My OnConnect and OnReceive Events Mthods-----------------

private void Client_OnConnect( string msg )
{
FileLogger Log = FileLogger.New;
Log.AppendToLogFile("Connected.");
Console.WriteLine( "Connected.");
}
private void Client_OnRecieve( string msg )
{

FileLogger Log = FileLogger.New;
Log.AppendToLogFile( msg );
Console.WriteLine(msg);
}

--------------My Multicasting code:-------------------------------

namespace DigiSoft.Multicasting
{
/// <summary>
/// Summary description for Multicasting.
/// </summary>
///
public delegate void OnRecieveDataEventHandler( string Message );
public delegate void OnConnectEventHandler(string Message );
public delegate void OnDisconnectEventHandler( string Message );
public delegate void OnErrorEventHandler( string errorMsg );

public class Multicasting
{
//Properties
public string MulticastGroup
{
get { return mygroupAddress; }
set { mygroupAddress = value; }
}

public int groupPort
{
get { return mygroupPort; }
set { mygroupPort = value; }
}

public int TTL
{
get { return myTTL; }
set { myTTL = value; }
}
private UdpClient thisClient;
private IPEndPoint RemoteEndPoint;
private string mygroupAddress;
private int mygroupPort;
private int myTTL;
private bool done;
private bool isRunning = false;

public void Start()
{
try
{
UdpClient udp = AsyncState as UdpClient;
thisClient= new UdpClient( mygroupPort );
thisClient.JoinMulticastGroup( IPAddress.Parse(mygroupAddress), myTTL );
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(mygroupAddress),
mygroupPort);

Thread myThread = new Thread( new ThreadStart( this.Listen ));
#if !CF
myThread.IsBackground = true;
#endif
myThread.Start();
isRunning = true;
if ( OnConnect != null)
OnConnect(string.Empty );

//send whereabouts to the group
byte[] bs = System.Text.Encoding.UTF8.GetBytes( Dns.GetHostByName(
Dns.GetHostName()).AddressList[0].ToString() + " has joined." ) ;
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);

}
catch(Exception e)
{
//Some error Message;
if(OnError!=null)
OnError("Error Connecting : " + e.Message);
done = true;
isRunning = false;
}
}

private void Listen()
{
done = false;
while(!done)
{

try
{
#if !CF
IPEndPoint IPEndPointNull = null;
#else

IPEndPoint IPEndPointNull = new IPEndPoint( IPAddress.Any,
this.mygroupPort );
#endif
byte[] bs = thisClient.Receive( ref IPEndPointNull);
string msg = System.Text.Encoding.UTF8.GetString(bs,0,bs.Length );

if ( OnRecieve != null )
OnRecieve(msg);
}
catch(Exception e)
{
//Some Error Message
if(OnError!=null)
OnError("Error Recieving: " + e.Message);
done = true;
isRunning = false;

}
}
}

public void Stop()
{

if ( !isRunning ) return ;

//Say your goodbyes to all the members of the group...
done = true;
isRunning = false;

byte[] bs = System.Text.Encoding.UTF8.GetBytes( Dns.GetHostByName(
Dns.GetHostName() ).AddressList[0].ToString() + " has left." ) ;
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);

#if CF
Thread.Sleep(300);
#endif

if( OnDisconnect!=null)
OnDisconnect( string.Empty );
try
{
thisClient.DropMulticastGroup(IPAddress.Parse(mygr oupAddress));
thisClient.Close();
}
catch(Exception e)
{
if(OnError!=null)
OnError("Error Closing: " + e.Message);
}
}

public void Send( string Message)
{
if ( !isRunning ) return ;

try
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(Message);
thisClient.Send(bs,(int) bs.Length, RemoteEndPoint);
}
catch(Exception e)
{
//Some Error Message
if(OnError!=null)
OnError("Error Sending: " + e.Message);
done = true;
isRunning = false;
}
}
public event OnRecieveDataEventHandler OnRecieve;
public event OnConnectEventHandler OnConnect;
public event OnDisconnectEventHandler OnDisconnect;
public event OnErrorEventHandler OnError;
}
}
Aug 28 '06 #5

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

Similar topics

3
by: david | last post by:
Hi, I would like to allow users to listen to live radio broadcasting within my ASP page, is this possible? Can you show me some code? Thanks in advance David
117
by: Peter Olcott | last post by:
www.halting-problem.com
2
by: Pavils Jurjans | last post by:
Hello, I wanted to propose a small class that would help to overcome the feature that's missing in MSIE. I'd like to get some feedback from people and, perhaps, improvements in code/other ideas:...
2
by: Islamegy® | last post by:
Hiiiiiii I'm working on a client server application which work like messnger.. I was able to capture the camera with no problem but now i want my my program to listen to incoming connection and...
1
by: Anthony | last post by:
i'm a newbie to .net remoting. I want to broadcast server event to client using .net remoting. I tried a few samples but they works only on Same machine or Lan environment. - Is there any...
0
by: salman | last post by:
hello i have client network (LAN) connected with server, and some client connected to server via RAS (Remote Access Service) and makes VPN. My problem is that when i broadcast message to...
1
by: Rain | last post by:
in UDP broadcasting, how do i know from which client was the message sent to the server? is there a way to know this without having to place the IP of the sender in the message itself? Thank you so...
1
by: =?Utf-8?B?RWl0YW4=?= | last post by:
Hello, I am writing a WinForm application that will broadcast a UDP datagram to multiple of embedded controllers. The controllers in return will send a response to the WinForm application. ...
1
luckysanj
by: luckysanj | last post by:
Dear Sir, Can you give me idea about Live Radio Broadcasting. I want to implement the Live Radio Broadcasting link on my web page to play radio on live. So i need basic php code for this. Your...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.