473,624 Members | 2,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

receiving data before Socket.EndRecei ve()

I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?
Here's the code:
public delegate void ReceivedPacketC allBack(Packet pack);
class PacketReceiver
{
private ReceivedPacketC allBack m_newPacket;
private IOBuffer m_socketAndBuff er;
private int m_blockSize;
private uint m_packetSize;
private uint m_receivedBytes ;
private List<bytem_hold Buffer;

public PacketReceiver( IOBuffer theSockBuff, int blockSize)
{
m_socketAndBuff er = theSockBuff;
m_blockSize = blockSize;
m_socketAndBuff er.ClearBuffer( );
m_packetSize = 0;
m_receivedBytes = 0;
//m_holdBuffer = new List<byte>();
}

public void NeedPacket(Rece ivedPacketCallB ack pack)
{
m_newPacket = pack;
}

//should make sure that we receive one and only one packet
public void ReceivePacket()
{
m_socketAndBuff er.ClearBuffer( );
if (m_socketAndBuf fer.IsConnected )
{
AsyncCallback callMe = new
AsyncCallback(R eceiveCallBack) ;
m_socketAndBuff er.ResizeByteBu ffer((uint)m_bl ockSize);
Console.WriteLi ne("The Buffer is " +
m_socketAndBuff er.m_buffer.Cou nt + " big in bytes.");

m_socketAndBuff er.m_sockMe.Beg inReceive(m_soc ketAndBuffer.m_ buffer,
SocketFlags.Non e, callMe, m_socketAndBuff er);
}
else
{
throw new Exception("The socket is no longer
connected.");
}
}

private void ReceiveCallBack (IAsyncResult ar)
{
m_socketAndBuff er = (IOBuffer)ar.As yncState;
if (m_socketAndBuf fer.IsConnected )
{
m_receivedBytes =
(uint)m_socketA ndBuffer.m_sock Me.EndReceive(a r);
m_holdBuffer = new List<byte>((int )m_receivedByte s);

m_holdBuffer.Ad dRange(m_socket AndBuffer.m_buf fer[0].Array);
m_socketAndBuff er.ClearBuffer( );
m_packetSize = Packet.ReadInt3 2FromBytes(m_ho ldBuffer,
0);
Console.WriteLi ne("The packet size is " + m_packetSize
+ "");
UInt32 bytesLeft = m_packetSize - (uint)(m_blockS ize -
4);
Console.WriteLi ne("We need to read " + bytesLeft + "
more bytes.");
if (bytesLeft 512000000)
{
Console.WriteLi ne("size to big");
}
m_socketAndBuff er.ResizeByteBu ffer(bytesLeft) ;

AsyncCallback callme = new
AsyncCallback(C reatePacket);

m_socketAndBuff er.m_sockMe.Beg inReceive(m_soc ketAndBuffer.m_ buffer,
SocketFlags.Non e, callme, m_socketAndBuff er);
}
}

private void CreatePacket(IA syncResult ar)
{
m_socketAndBuff er = (IOBuffer)ar.As yncState;
if (m_socketAndBuf fer.IsConnected )
{
m_receivedBytes +=
(uint)m_socketA ndBuffer.m_sock Me.EndReceive(a r);

m_holdBuffer.Ad dRange(m_socket AndBuffer.m_buf fer[0].Array);
if (m_receivedByte s < (m_packetSize + 4))
{
uint leftOver = m_receivedBytes - m_packetSize +
4;
m_socketAndBuff er.ResizeByteBu ffer(leftOver);
AsyncCallback callMeNow = new
AsyncCallback(C reatePacket);

m_socketAndBuff er.m_sockMe.Beg inReceive(m_soc ketAndBuffer.m_ buffer,
SocketFlags.Non e, callMeNow, m_socketAndBuff er);
}
Packet thePacket = Packet.ParseByt es(m_holdBuffer ,
m_blockSize);
m_newPacket(the Packet); //send the packet to
whoever needs it (delegate)
}
}
}

Aug 3 '07 #1
7 3174
da*********@gma il.com wrote:
I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?
Here's the code:
That is both not enough code and too much, all at the same time. You
are missing half of the connection (the sending side) as well as the
implementation of IOBuffer, and as well you have included a fair amount
of code that is likely not necessary to reproduce the issue (in fact,
unless IOBuffer is directly related to the problem, you should post code
that doesn't even include it).

And you have not precisely described what the actual problem is. What
output do you get, and what output do you expect instead?

So, if you really want someone to spend more than a few moments with
your code, you should distill it down into something that is
concise-but-complete while reliably reproducing the problem. Post that
along with a precise problem description.

That said, as near as I can tell from my quick scan of your code, you
appear to deliver an assembled "packet" whether it's completed or not.
I would expect that to be a problem.

There are plenty of other things I would change about the code, but that
stands out as being particularly likely to produce incorrect results.

Pete
Aug 3 '07 #2
On Aug 2, 8:44 pm, Peter Duniho <NpOeStPe...@Nn OwSlPiAnMk.comw rote:
darthgha...@gma il.com wrote:
I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?
Here's the code:

That is both not enough code and too much, all at the same time. You
are missing half of the connection (the sending side) as well as the
implementation of IOBuffer, and as well you have included a fair amount
of code that is likely not necessary to reproduce the issue (in fact,
unless IOBuffer is directly related to the problem, you should post code
that doesn't even include it).

And you have not precisely described what the actual problem is. What
output do you get, and what output do you expect instead?

So, if you really want someone to spend more than a few moments with
your code, you should distill it down into something that is
concise-but-complete while reliably reproducing the problem. Post that
along with a precise problem description.

That said, as near as I can tell from my quick scan of your code, you
appear to deliver an assembled "packet" whether it's completed or not.
I would expect that to be a problem.

There are plenty of other things I would change about the code, but that
stands out as being particularly likely to produce incorrect results.

Pete
Here is the section of code where I use the PacketReceiver:
private void EndStart(IAsync Result ar)
{
Socket temp = (Socket)ar.Asyn cState;
if (temp.Connected )
{
int sentBytes = temp.EndSend(ar );
List<ArraySegme nt<byte>tempBuf fer = new
List<ArraySegme nt<byte>>();
tempBuffer.Add( new ArraySegment<by te>(new byte[255]));
receiveBuffer.m _buffer = tempBuffer;
AsyncCallback callMe = new
AsyncCallback(E ndReceiveVersio nString);

receiveBuffer.m _sockMe.BeginRe ceive(receiveBu ffer.m_buffer,
SocketFlags.Non e, callMe, receiveBuffer);
}
}

private void EndReceiveVersi on(IAsyncResult ar)
{
Encoder theEncoder = new Encoder();
IOBuffer temp = (IOBuffer)ar.As yncState;
if (temp.m_sockMe. Connected)
{
int receivedBytes = temp.m_sockMe.E ndReceive(ar);

Packet sendAlgs = new Packet();
sendAlgs.Fill(s endData);
ArraySegment<by tetoBuff = new
ArraySegment<by te>(sendAlgs.Ge tPacketInBytes( ));
sendBuffer.m_bu ffer.Add(toBuff );
sendBuffer.m_so ckMe.BeginSend( sendBuffer.m_bu ffer,
SocketFlags.Non e, callMe, sendBuffer);
}
}
I have not experienced problems sending, just receiving. The output I
am seeing in the console is data sent from the client, but only the
first part of it. The rest of the data sent from the client is in the
buffer like it should be. The packet is assembled by first reading
the length (which should be the first of the packet), then doing
another receive call to get the rest of the packet. Since some of the
data received is sent to the console instead of the buffer, I get a
bad length when I try to do the second receive call. For example, if
the client sends a packet like this:
23somedata
the console would display the following (which it shouldn't):
23som
and the buffer would contain:
edata
Does that make sense?
Thanks for your time.

Aug 3 '07 #3
On Aug 2, 9:43 pm, darthgha...@gma il.com wrote:
On Aug 2, 8:44 pm, Peter Duniho <NpOeStPe...@Nn OwSlPiAnMk.comw rote:
darthgha...@gma il.com wrote:
I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?
Here's the code:
That is both not enough code and too much, all at the same time. You
are missing half of the connection (the sending side) as well as the
implementation of IOBuffer, and as well you have included a fair amount
of code that is likely not necessary to reproduce the issue (in fact,
unless IOBuffer is directly related to the problem, you should post code
that doesn't even include it).
And you have not precisely described what the actual problem is. What
output do you get, and what output do you expect instead?
So, if you really want someone to spend more than a few moments with
your code, you should distill it down into something that is
concise-but-complete while reliably reproducing the problem. Post that
along with a precise problem description.
That said, as near as I can tell from my quick scan of your code, you
appear to deliver an assembled "packet" whether it's completed or not.
I would expect that to be a problem.
There are plenty of other things I would change about the code, but that
stands out as being particularly likely to produce incorrect results.
Pete

Here is the section of code where I use the PacketReceiver:
private void EndStart(IAsync Result ar)
{
Socket temp = (Socket)ar.Asyn cState;
if (temp.Connected )
{
int sentBytes = temp.EndSend(ar );
List<ArraySegme nt<byte>tempBuf fer = new
List<ArraySegme nt<byte>>();
tempBuffer.Add( new ArraySegment<by te>(new byte[255]));
receiveBuffer.m _buffer = tempBuffer;
AsyncCallback callMe = new
AsyncCallback(E ndReceiveVersio nString);

receiveBuffer.m _sockMe.BeginRe ceive(receiveBu ffer.m_buffer,
SocketFlags.Non e, callMe, receiveBuffer);
}
}

private void EndReceiveVersi on(IAsyncResult ar)
{
Encoder theEncoder = new Encoder();
IOBuffer temp = (IOBuffer)ar.As yncState;
if (temp.m_sockMe. Connected)
{
int receivedBytes = temp.m_sockMe.E ndReceive(ar);

Packet sendAlgs = new Packet();
sendAlgs.Fill(s endData);
ArraySegment<by tetoBuff = new
ArraySegment<by te>(sendAlgs.Ge tPacketInBytes( ));
sendBuffer.m_bu ffer.Add(toBuff );
sendBuffer.m_so ckMe.BeginSend( sendBuffer.m_bu ffer,
SocketFlags.Non e, callMe, sendBuffer);
}
}
I have not experienced problems sending, just receiving. The output I
am seeing in the console is data sent from the client, but only the
first part of it. The rest of the data sent from the client is in the
buffer like it should be. The packet is assembled by first reading
the length (which should be the first of the packet), then doing
another receive call to get the rest of the packet. Since some of the
data received is sent to the console instead of the buffer, I get a
bad length when I try to do the second receive call. For example, if
the client sends a packet like this:
23somedata
the console would display the following (which it shouldn't):
23som
and the buffer would contain:
edata
Does that make sense?
Thanks for your time.
Also, please feel free to make suggestions on how I can improve my
code. I'm really new to this and would appreciate any tips anyone
might have. If there are any good books on sockets or writing good
code please feel free to suggest them.
Thanks for your time.

Aug 3 '07 #4
da*********@gma il.com wrote:
[...]
Now comes the hard
part, the redesign. Would it be better to read one byte at a time
looking for line feed or read chunks looking for the same thing and
saving the rest? If anyone knows of some good examples or articles on
good ways to design this type of thing please feel free to suggest
them.
Generally speaking, you should receive larger blocks at a time, to make
most efficient use of the network i/o. Then you can parcel that data
out as needed to the actual application end of things.

As another suggestion regarding your code: IMHO, it's not a good idea to
have two different receive callbacks. I understand that you have
different things to do when receiving the data, and that's what led to
the two different callbacks. But your network i/o should be more
separated from the application logic than that (see above).

Even once you get things separated better, IMHO it will still make more
sense to have a general-purpose application data-handling method, but at
least if you don't do it that way, your actual network i/o code remains
simple.

Pete
Aug 3 '07 #5
On Aug 3, 2:58 pm, Peter Duniho <NpOeStPe...@Nn OwSlPiAnMk.comw rote:
darthgha...@gma il.com wrote:
[...]
Now comes the hard
part, the redesign. Would it be better to read one byte at a time
looking for line feed or read chunks looking for the same thing and
saving the rest? If anyone knows of some good examples or articles on
good ways to design this type of thing please feel free to suggest
them.

Generally speaking, you should receive larger blocks at a time, to make
most efficient use of the network i/o. Then you can parcel that data
out as needed to the actual application end of things.

As another suggestion regarding your code: IMHO, it's not a good idea to
have two different receive callbacks. I understand that you have
different things to do when receiving the data, and that's what led to
the two different callbacks. But your network i/o should be more
separated from the application logic than that (see above).

Even once you get things separated better, IMHO it will still make more
sense to have a general-purpose application data-handling method, but at
least if you don't do it that way, your actual network i/o code remains
simple.

Pete
I'll give that a shot. Thanks again for your time.

Aug 3 '07 #6
You're trying to do the same sorts of things we do in our XMPP SDK.

We read from the various socket streams, parse out XML Fragments, turn them
into packets, match them against classes, instantiate the right object,
serialize the xml into the object, and then raise the correct event.

Our SDK has source code available, and you can pull it down and look at how
we're doing everything:
http://developers.coversant.net/Down...3/Default.aspx

What you're looking for is (mostly) found in the two classes:
Coversant.SoapB ox.Base.XMPPSoc ket
Coversant.SoapB ox.Base.XMLStre amReceiver

Our approach is very scalable, and quite reliable. Our use of socket buffers
that comes out of a buffer pool for reads/write, minimizes heap
fragmentation.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

<da*********@gm ail.comwrote in message
news:11******** *************@e 16g2000pri.goog legroups.com...
>I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?

Aug 3 '07 #7
On Aug 3, 4:29 pm, "Chris Mullins [MVP]" <cmull...@yahoo .comwrote:
You're trying to do the same sorts of things we do in our XMPP SDK.

We read from the various socket streams, parse out XML Fragments, turn them
into packets, match them against classes, instantiate the right object,
serialize the xml into the object, and then raise the correct event.

Our SDK has source code available, and you can pull it down and look at how
we're doing everything:http://developers.coversant.net/Down...3/Default.aspx

What you're looking for is (mostly) found in the two classes:
Coversant.SoapB ox.Base.XMPPSoc ket
Coversant.SoapB ox.Base.XMLStre amReceiver

Our approach is very scalable, and quite reliable. Our use of socket buffers
that comes out of a buffer pool for reads/write, minimizes heap
fragmentation.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVPhttp://www.coversant.c om/blogs/cmullins

<darthgha...@gm ail.comwrote in message

news:11******** *************@e 16g2000pri.goog legroups.com...
I am having mixed results with asynchronous socket receives.
Sometimes I get the right information back from the buffer, other
times I get some of the data that should be in the buffer printed out
to the console. That data is printed out to the console before I even
call Socket.EndRecei ve(). After that call, I get the rest of the data
that wasn't printed out to the console in the buffer. Anyone have
any idea what is going on?
Thank you. I'll take a look at that over the weekend and see what I
can learn from it.
Thanks again for the time.

Aug 4 '07 #8

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

Similar topics

4
1834
by: Pete Davis | last post by:
I've written an async socket server app and I'm having an issue with the EndReceive() call. My begin receive call is: sockState.RemoteSocket.BeginReceive(sockState.ReceiveBuffer, 0, SocketState.BufferSize, 0, new AsyncCallback(this.ReadCallback), sockState); The ReadCallback() method begins:
4
7586
by: Brian Rice | last post by:
I have a socket application that is sending and receiving packets asynchronously. It works great except, when I receive packets that are larger than my receive buffer which then generate several EndReceive calls... these calls seem to be sometimes coming out of order. For example, the following is from my log file: Connection at 5/1/2004 11:39:14 AM SENT> ZZZ:1:FMZZZ:ID1234:PWAAAA:VR100:\0 RCVD>...
0
1265
by: André Betz | last post by:
Hi, I've established a TCP-Socket Connection and now I want to receive datas. So I called BeginReceive where I set the receiving buffer and length. Now in the asynchronous CallBack-Function I call EndReceive and get the length of rceived datas. After receiving datas I call the Beginreceive-Function again. So my question is now what is if the send datas is greater than the receiving buffer? Ok, I know, I will get it in the next...
6
13139
by: Steve Richter | last post by:
I dont get the point of socket.BeginReceive and socket.EndReceive. As I understand it, BeginReceive will start a 2nd thread, call the ReceiveCallback delegate in the 2nd thread, then block until the socket.EndReceive method called in the 2nd thread receives some data from the socket. If the 1st thread will block until the 2nd thread receives some data from the socket, what is the point of starting up the 2nd thread? I am aware I can...
0
1048
by: Christoph Bisping | last post by:
Hello! I'm not sure if this is the right place to ask my question... According to the docs, it is possible to receive udp datagrams asynchronous using the Socket-class and its .BeginRecive(From) method. My problem is that I can't figure out how big the receive-buffer should be. When my programs fires the receive-callback function, I call the EndReceive(From) method to copy the received datagrams to the buffer that I've supplied...
7
3932
by: Crirus | last post by:
Hi all! I use a webClient for requesting data from a server of mine. Should I worry about long ammount of data sent by server in the client side? Or, another way, should I send some kind of a terminator sign in the data in order to realise in the client that all data arrived? -- Ceers, Crirus
2
6869
by: Macca | last post by:
My app has an asynchronous socket server. It will have 20 clients connected to the server. Each client sends data every 500 millisecondsThe Connections once established will not be closed unless there is a problem with the connection. I need to know which client has sent the incoming data as each client has its own buffer on my "server" app. I am using the standard asynch socket code from MSDN to listen for connections and they...
8
11005
by: Dinsdale | last post by:
I am trying to write a Tcp "Server" that opens a class that wraps a tcp socket when a new connection is made (Listener.AcceptSocket()). Everything is going swimmingly except when I try to close the socket during a read and I get the following error: <error_msg> An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in system.dll Additional information: The I/O operation has been aborted because of
0
3566
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 actual files that are sent to the computer as part of http or ftp. Basically if a user browse a page...
0
8688
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
8635
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
8352
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
8494
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7178
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...
1
6115
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2614
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
1496
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.