473,563 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unconnected udp socket not receiving anything

Hi

I have a small program listening to UDP broadcast datagrams that are
periodically sent out. It will stop listening for a certain period if either
a sufficient number of packets has been received (this is triggered from a
class not in the sample code), or if there has been no data on the net for a
certain period. During the time where I don't want any packets, I set my
socket receive buffer size to zero.

The problem is, when I used a UDPClient, I was always getting data that was
sent during the period where no listening took place (and changing the
buffer size didn't help), so I'm using sockets directly. However, I don't
receive a single packet now and I have no clue why. sock.Available is always
zero, even if I send a thousand UDP datagrams during the active period.
Here's my code:

public class Receiver
{
IPEndPoint remoteSender;
EndPoint tempRemoteEP;
byte[] packet;
public Thread thread;
bool listening;
Timer tim;
TimerState s;
public int nbPackets;
int seqNo;
Socket sock;
int nbBytesRx;

public Receiver()
{
sock = new Socket(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.Broadcast, 1);
remoteSender = new IPEndPoint(IPAd dress.Any,0);
tempRemoteEP = (EndPoint)remot eSender;
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.ReceiveBuffer , 0);
listening = false;
nbPackets = 0;
packet = new byte[1024];
s = new TimerState();
TimerCallback timerDelegate = new TimerCallback(t his.timeToSleep );
tim = new Timer(timerDele gate, null, Timeout.Infinit e, Timeout.Infinit e);
ThreadStart startMethod = new ThreadStart(thi s.run);
thread = new Thread(startMet hod);
thread.Start();
thread.Suspend( );
}

/**
* method that is running when the thread is active
* receives a packet from the network and processes it
*/
public void run()
{
while (true)
{
if (sock.Available > 0)
{
this.nbBytesRx = sock.ReceiveFro m(packet, ref tempRemoteEP);
nbPackets++;
seqNo = BitConverter.To Int16(packet, 0);
Console.Write(n bPackets.ToStri ng() + ":" + seqNo.ToString( ) + " / " );
}
}
}

/**
* resumes the thread
*/
public void activate()
{
if (thread.ThreadS tate == ThreadState.Sus pended || thread.ThreadSt ate ==
ThreadState.Sus pendRequested)
{
Console.WriteLi ne("activated") ;
tim.Change(5000 , 5000);
if (sock.Available > 0)
{
Console.Write(" pending data");
}
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.ReceiveBuffer , 8192);
thread.Resume() ;
}
else
{
Console.WriteLi ne("thread was already running");
}
this.listening = true;
}

/**
* suspends the thread
*/
public void deactivate()
{
if (thread.ThreadS tate == ThreadState.Run ning)
{
Console.WriteLi ne("\r\ndeactiv ated. " + this.nbPackets. ToString() + "
packets received");
tim.Change(Time out.Infinite,Ti meout.Infinite) ; // disable timer for the
time being
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.ReceiveBuffer , 0);
thread.Suspend( );
}
else
{
Console.WriteLi ne("thread was already inactive");
}
this.listening = false;
this.nbPackets = 0;
}

public void shutDown()
{
if (thread.ThreadS tate == ThreadState.Sus pended)
thread.Resume() ;
thread.Abort();
}

/**
* Callback for the timer. Checks whether it's time to suspend the thread
because no new packets
* are coming in
*/
public void timeToSleep(Obj ect state)
{
//TimerState stat = (TimerState)sta te;
if (this.nbPackets > s.counter) // new packets received in current period
{
s.counter = this.nbPackets;
}
else
{
if (this.listening )
{
this.deactivate ();
s.counter = 0;
}
}
}
}

public struct TimerState
{
public int counter;
public Timer tim;
}

and to test I use this code which periodically activates and deactivates the
receiver.

static void Main(string[] args)
{
Receiver rec = new Receiver();
while (true)
{
rec.activate();
Thread.Sleep(10 000);
rec.deactivate( );
Thread.Sleep(10 000);
}
}

Any help would be much appreciated.

Regards

Stephan Steiner
Nov 15 '05 #1
3 7788
"Stephan Steiner" <st*****@isuiss e.com> wrote in message news:<O#******* *******@TK2MSFT NGP11.phx.gbl>. ..
The problem is, when I used a UDPClient, I was always getting data that was
sent during the period where no listening took place (and changing the
buffer size didn't help), so I'm using sockets directly. However, I don't
receive a single packet now and I have no clue why. sock.Available is always
zero, even if I send a thousand UDP datagrams during the active period.

Stephan -

I did not see where you bound the socket to the UDP port that the
broadcast packets are using:

IPEndPoint iep = new IPEndPoint(IPAd dress.Any, 9050);
sock.Bind(iep);

This enables the ReceiveFrom() method to accept packets destined
for UDP port 9050. Hope this makes sense.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyT...471433012.html
Nov 15 '05 #2
"Stephan Steiner" <st*****@shockf ish.com> wrote in message news:<uX******* *******@tk2msft ngp13.phx.gbl>. ..
Not only makes it sense, now it works the way it should :) Thanks a bunch.
But while we're at the subject, the thing with the socket buffer is still
somewhat bothering me. As you can see from the source, I'm setting the
socket receive buffer size to zero before going to sleep. When I wake back
up, I reset the buffer to its standard size. The thing is, while the socket
does not accept any new packets when the buffer size is zero, one packet -
the first one being sent after the buffer size is set to zero - is somehow
kept in the system, and as soon as I reset the buffer size to its normal
value, that packet is added to the buffer. Where is that packet coming from
and why is it kept while the rest is dumped? I suppose it has something to
do with an underlying driver but I find it rather weird that one single
packet is kept.. no reasonable device driver buffer should be limited to one
750byte datagram, should it? After all, the Ethernet MTU is 1500bytes so if
it's the NIC driver buffer, it should at least hold two of my datagrams.

This is exactly the behavior that I pointed out in an earlier post
to your other thread. I do not have an explanation for this. My guess
is that there must be a buffer somewhere between the socket buffer and
the application that is allowing one packet (regardless of size) to be
accepted. Maybe someone else knows more about this.
And another thing I'm wondering about: why does a socket, or UDPClient for
the matter, require a certain setup time? I found that in all my tests,
during my first data burst, there would be a gap in the reception. The first
12 packets would be received, then a buffer wold overflow and packets be
dropped until the receiver can somehow catch up. From that point on,
everything works as it should. During my tests I also found that if at the
very beginning (before even starting my thread), I send one packet and
receive it immediately thereafter, the socket/UDPClient seems to be properly
initialized and no packets of my first databurst will be lost. Is this a
known problem?


I have not experienced this problem. Since you are using a
background thread to read packets there is some set-up time necessary
for the thread to be created and get started. This may be causing your
initial packet drops, which clean up once the thread is established
and running.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyT...471433012.html
Nov 15 '05 #3
HI

I have not experienced this problem. Since you are using a
background thread to read packets there is some set-up time necessary
for the thread to be created and get started. This may be causing your
initial packet drops, which clean up once the thread is established
and running.

No, this isn't it. The thread is initialized and running well before I start
receiving packets. The same is also true for my two previous sender and
receiver (I mailed those to you a while back)... it takes much longer for
the first send/receive than for subsequent ones. When stepping through any
of those programs (the old ones were single threaded, now the receiver is
threaded but the sender is still a singlethread app), I notice that the
first send/receive command blocks for a period of about a second, and any
subsequent operations are performed as quickly as any other line I step
through in the debugger.

If we take the following snippet as an example:

UdpClient updClient = new UdpClient(local Port);
Byte[] packet = new Byte[packetSize];
int nBytesSent = 0;
Byte[] seqNr = null;
for (short i = 0; i < nbPackets; i++ )
{
seqNr = BitConverter.Ge tBytes(i);
packet[0] = seqNr[0];
packet[1] = seqNr[1];
nBytesSent = updClient.Send( packet, packet.Length, address, remotePort);
Console.WriteLi ne("Packet # " + i + " byte3 " + packet[2] + " byte2 "
+ packet [1] + " byte1 " + packet[0]);
Thread.Sleep(10 );
}
The first run of the for loop will take significantly longer than any
subsequent loop. When debugging, the first time updClient.Send( ..) is
called, the commandline window (I'm using it in a cli project) quickly comes
on screen, then disappears again as the Console.WriteLi ne line is executed.
This only happens during the first run of the loop. This leads me to believe
that somehow, the UdpClient (and sockets as well because my socket based
code exhibits the same issue) is only properly set up, once a send or
receive operation is made. I've tried this out on two different computers
having two different operating systems (W2k, XP) and this issue was present
on both so I'm leaning towards a software issue here. As a workaround, I
perform a send/receive during the setup phase of any sender / receiver
class, and then when I actually want to send / receive I can do so without
any delays (and in the case of receiving: without loosing packets).

Stephan
Nov 15 '05 #4

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

Similar topics

3
2615
by: Aaron | last post by:
tcpclient socket webrequest what are each used for? I read some reference books and did some research on the internet, but I'm still confused. could someone clarify this for me? Thanks, Aaron
3
4617
by: Robert A. van Ginkel | last post by:
Hello Fellow Developer, I use the System.Net.Sockets to send/receive data (no tcpclient/tcplistener), I made a receivethread in my wrapper, the receivethread loops/sleeps while waiting for data and then fires a datareceived event. Within the waitingloop there is a timeout function, but I want the the 'last-time-socket-used' variable set...
3
3682
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...
7
8720
by: e2wugui | last post by:
thread1: while 1: buf = s.read() process(buf) thread2: while 1: buf = getdata() s.write(buf)
2
15312
by: djc | last post by:
I read a network programming book (based on framework 1.1) which indicated that you should 'never' use the RecieveTimeout or the SendTimeout 'socket options' on TCP sockets or you may loose data. I now see the socket.RecieveTimeout 'property' in the visual studio 2005 help documentation (framework 2.0) and it has example of it being used with...
3
4277
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the receiver is running within Process1. If I move the receiver into Process2 then its fast. Please can someone explain.
0
3559
by: george585 | last post by:
Hello! I am new to network programming, and understand just basics. Using some sample code, and having read documentation, I managed to create a simple app in C# and VB.NET. The application is supposed to do the following: monitor ALL INCOMING TCP traffic on the local computer, and save certain parts of it as files - not log files though, but...
4
16065
by: O.B. | last post by:
I have a socket configured as TCP and running as a listener. When I close socket, it doesn't always free up the port immediately. Even when no connections have been made to it. So when I open the socket again, the bind fails because the port is still in use. When I execute the code in "debug" mode, the problem never occurs. When I...
4
7053
by: Zytan | last post by:
This may be the dumbest question of all time, but... When I set the packet size, does it mean ALL packets are that size, no matter what? Let's say the packet size is 8KB, and I send a 5 byte "hello", will it cause 8KB of bandwidth, or 5 bytes (plus TCP/IP packet header, as well, of course). (Btw, I 'set' the packet size via...
0
7658
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...
0
7579
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...
0
7877
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. ...
0
8101
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...
1
7631
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...
0
7943
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...
1
5479
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...
0
3615
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2077
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

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.