473,848 Members | 1,835 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 41967
"Stephan Steiner" <st*****@shockf ish.com> wrote in message news:<u4******* ******@TK2MSFTN GP11.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.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.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.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.ReceiveBuffer , 0);


I have already tried that yesterday (I was going through the entire
system.net.sock et 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.GetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.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(local Port);
remoteSender = new IPEndPoint(IPAd dress.Any,0);
sock = this.Client;
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.Broadcast, 1);
int receiveBuffer = (int)sock.GetSo cketOption(Sock etOptionLevel.S ocket,
SocketOptionNam e.ReceiveBuffer );
sock.SetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.ReceiveBuffer , 0);
int sent = receiver.Send(n ew byte[2], 2, "192.168.1.255" , 14888);
packet = receiver.Receiv e(ref remoteSender);
//Object o = sock.GetSocketO ption(SocketOpt ionLevel.Socket ,
SocketOptionNam e.PacketInforma tion);
//this.handler = handler;
listening = false;
nbPackets = 0;
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();
receiveBuffer = (int)sock.GetSo cketOption(Sock etOptionLevel.S ocket,
SocketOptionNam e.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.Receiv e(ref remoteSender);
nbPackets++;
seqNo = BitConverter.To Int16(packet, 0);
Console.Write(n bPackets.ToStri ng() + ":" + seqNo.ToString( ) + " / " );
//o.ToString();
// spit out packet for processing handler.process Packet(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(1000 0, SelectMode.Sele ctRead)

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.Receiv e(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.Availabl e
parameter. Funny enough, before reactivating my receiver thread,
socket.Availabl e returns zero, but when I do a UdpClient.Recei ve() 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
1346
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 handler to clear the buffer because the buffering is inside my own error handler already.
3
1932
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 display the table until it receives the closing </table> tag. The question is, am I correct in saying that the buffer on the server is CLEARED when i = 500? It will be empty for a split second until the loop resumes again. Am I correct? Dim i i =...
2
1955
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. // note, i know the following is not an entire DHCP packet, I just didn't want this msg to get too long. public struct DHCPPacket { public byte op; public byte htype;
3
8531
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, each contains a status as to the success or failure of the particular process. I want to be able to send to the client each output string at it happens. The way it is working right now is that it is storing the output until all of the functions...
2
6810
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 that is sent to the device is instructions for that piece of hardware, and data recieved is just responses from that hardware. When a timeout happens, for some reason extra data is stored inside the buffer, so when the timeout is over, that...
6
39406
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 unwanted data when i use recv(). A part of my server code is like this: int bytesRecv = SOCKET_ERROR; char recvbuf=""; int ch ; bytesRecv = recv( clientSocket, recvbuf, 1, 0 );
5
2873
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 same thing. ?
0
1345
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
2097
by: devgupta01 | last post by:
What is the flushing the buffer? could u please explain with example.
0
11005
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10665
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10723
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,...
0
9501
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7070
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();...
0
5735
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...
1
4544
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
2
4139
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3177
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.