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

flushing a socket buffer

Hi

I have a networking application that periodically needs to go into sleep
mode (from an application point of view, I'm simply suspending the receiver
thread until it's time to start listening to incoming packets again). The
packets I'm interested in are UDP broadcasts, so they are simply dropped
when nobody application is listening at the specified port. However, when I
initialize my receiver, there's a socket listening at the appropriate port,
so even when I suspend reception of incoming packets, the socket buffer is
still being filled, and only when it's full, will packets be dropped. I'd
like to not have any "old" packets after re-enabling the receiver, so I have
to somehow flush the receive buffer associated to my socket, but I haven't
found any way to do so. Note that I'm not using any streams on top of the
socket (actually I'm not even use a socket directly, I'm using a UDPClient,
but it allows you to retreive the underlying socket so operations on that
level would nevertheless be possible).
Any ideas?

Regards
Stephan Steiner
Nov 13 '05 #1
4 41671
"Stephan Steiner" <st*****@shockfish.com> wrote in message news:<u4*************@TK2MSFTNGP11.phx.gbl>...

However, when I
initialize my receiver, there's a socket listening at the appropriate port,
so even when I suspend reception of incoming packets, the socket buffer is
still being filled, and only when it's full, will packets be dropped. I'd
like to not have any "old" packets after re-enabling the receiver, so I have
to somehow flush the receive buffer associated to my socket, but I haven't
found any way to do so.


Stephan -

You can not flush the socket buffer data without reading what's in
there, but you can prevent datagrams from being stored in the buffer
by reducing the size of the socket buffer.

To accomplish this you need to set the socket receive buffer to 0
before suspending reception of incoming packets. You can use the
SetSocketOption() method to force the receive buffer to 0:

sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, 0);

This will prevent additional datagrams from entering the socket
buffer until you are ready to read them (you probably want to set the
buffer back to a reasonable size when you are ready to read again).
Hope this helps solve your problem.

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 13 '05 #2
Hi


To accomplish this you need to set the socket receive buffer to 0
before suspending reception of incoming packets. You can use the
SetSocketOption() method to force the receive buffer to 0:

sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, 0);


I have already tried that yesterday (I was going through the entire
system.net.socket namespace to try and find a solution), but it didn't work
as it should. I've set the ReceiveBuffer to zero, and I've verified that the
buffer size has indeed by set to zero using
sock.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer), however despite it being zero, when I send
packets while the receiver is inactive, once I activate it again, I still
have 13 of the packets I sent during the inactive period. In fact, if I set
the buffer to zero and leave it like that during the whole program run, I
still receive incoming packets even when the receiver is active. I do no
longer get all of them, but shouldn't I get none if I have a buffer size
that doesn't even allow to store one single of my 750 byte packets (722 byte
payload plus IP and UDP headers)?

Here's the code snippet I'm using:

UdpClient receiver;
IPEndPoint remoteSender;
Byte[] packet;
public Thread thread;
bool listening;
//PacketHandler handler;
Timer tim;
TimerState s;
public int nbPackets;
int seqNo;
Socket sock;

public Receiver(int localPort) : base()
{
receiver = new UdpClient(localPort);
remoteSender = new IPEndPoint(IPAddress.Any,0);
sock = this.Client;
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
int receiveBuffer = (int)sock.GetSocketOption(SocketOptionLevel.Socket ,
SocketOptionName.ReceiveBuffer);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, 0);
int sent = receiver.Send(new byte[2], 2, "192.168.1.255", 14888);
packet = receiver.Receive(ref remoteSender);
//Object o = sock.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.PacketInformation);
//this.handler = handler;
listening = false;
nbPackets = 0;
s = new TimerState();
TimerCallback timerDelegate = new TimerCallback(this.timeToSleep);
tim = new Timer(timerDelegate, null, Timeout.Infinite, Timeout.Infinite);
//
ThreadStart startMethod = new ThreadStart(this.run);
thread = new Thread(startMethod);
thread.Start();
receiveBuffer = (int)sock.GetSocketOption(SocketOptionLevel.Socket ,
SocketOptionName.ReceiveBuffer);
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)
{
packet = receiver.Receive(ref remoteSender);
nbPackets++;
seqNo = BitConverter.ToInt16(packet, 0);
Console.Write(nbPackets.ToString() + ":" + seqNo.ToString() + " / " );
//o.ToString();
// spit out packet for processing handler.processPacket(packet);
}
}

I have a main program that suspends and resumes the thread every 10 seconds.
The timer will shut down the receiver after 5 seconds if nbPackets has not
been received (in other words: when there has been no new packet). I use the
same code to send packets like last time (maybe you remember, I sent you the
code because I was having a problem with UdpClient not receiving all packets
on my machine at work.. ).

Stephan
Nov 13 '05 #3
>-----Original Message-----
It gets even better.

As a workaround for my problem, I tried to read any pending data from thesocket, before activating the listening thread again. To find out if there'spending data I used this code:

sock.Poll(10000, SelectMode.SelectRead)

which according to the documentation should return true if there's data tobe read. However, it always returns false. The next line in the program isalready the reactivation of the thread (thread.resume()), and subsequentcalls to receiver.Receive(ref remoteSender) (receiver is a UDPClient) yieldpackets that have been sent during the period where the receiver thread wasdeactivated. I find this highly confusing because we're talking aboutpackets that have been sent well before I polled the socket to see ifthere's any pending data.

Stephan -

I think your problem is that you are using the
UdpClient "helper function", then drilling down to the low-
level socket and trying to perform functions there. Its
been my experience that's its best to perform all of your
operations at the same "level" - check for data at the
same level your are reading it from.

When you set the ReceiveBuffer size to 0, you are
disabling the socket level buffers. When data is received
by the socket, it must attempt to forward it to the next
level buffer. With a normal socket, that means to the next
Receive() method in your app. With the UdpClient object,
that must not be the case. Something must be buffering
data within the UdpClient object.

My suggestion would be to just use a plain-old Socket
object, and try this again. In my tests, I noticed that
the socket did hold 1 datagram in its buffer before
dropping subsequent packets (and the size of the datagram
didn't seem to matter). I don't know why this is the case -
I'll keep investigating (unless of course someone else on
this list knows why :). You may have to account for that
in your code. Hope this sheds some light on your problem.

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/WileyTitle/productCd-
0471433012.html
Nov 13 '05 #4
I've been doing some more testing and came across the socket.Available
parameter. Funny enough, before reactivating my receiver thread,
socket.Available returns zero, but when I do a UdpClient.Receive() prior to
re-enabling the receiver thread, I can read out datagrams that have been
sent during the inactive period.
Either this is another funny issue with the computer at work (I'll test at
home to make sure), or UdpClient has its own buffer and keeps on reading
datagrams from the socket until its own buffer is full so I'll try using
sockets directly as a last hope attempt.

If anyone has any ideas, I'd really appreciate them.. if I can't ensure that
I get no old data, I have to create a really nasty workaround based on my
packet sequence numbers, which will certainly only make things worse and
lead to unwanted results in the end.

Stephan
Nov 15 '05 #5

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

Similar topics

0
by: micha | last post by:
whenever an error occurs after ob_start() the buffer is flushed and the content printed. 1. is that standard behaviour? 2. if yes, how to prevent it? micha p.s. i can't use my own error...
3
by: Andyza | last post by:
In the following code when i = 500 the buffer on the server is flushed to the client. However, because the content that is sent to the browser contains an html table Internet Explorer does not...
2
by: allen | last post by:
I have an async socket callback for a UDP socket. When the callback is fired after receiving a packet, I want to map the packet to a structure I have. note, all unsafe code blocks here. //...
3
by: Eric | last post by:
Good afternoon, Can anyone help me with flushing the buffer in ASP.NET. I have a set of functions that perform a series of maintainence operations. As these functions are called sequentially,...
2
by: Kiran | last post by:
Hello Everybody! I am writing a networking application in python for a small piece of hardware, in which there could sometimes be timeouts. I am using sockets to communicate to this device. Data...
6
by: ppuniversal | last post by:
Can anyone tell me how to flush a socket stream in C++. I am making an Client Server application in C++ and use the send() and recv() functions. i want to flush the socket buffer as i am getting...
5
by: arnuld | last post by:
this is from mentioned section. i did not understand some things here: it means "flushing the buffer" and "writing to output device" are SAME thing, these are just 2 different names for the...
0
by: Diego F. | last post by:
Hello. I need to know what is the maximum size of the socket buffer. According to my test, it is 8192 bytes. Is it correct? -- Regards, Diego F.
1
by: devgupta01 | last post by:
What is the flushing the buffer? could u please explain with example.
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
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,...
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...

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.