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:ID1 234:PWAAAA:VR10 0:\0
RCVD> ZZZ:1:FMZZZ:SW2 4657:CNUS:TO480 :TX113731:DX050 12004:DEOCX OPR
RCVD> ACASHTESTSX:\0
Connection at 5/1/2004 11:39:32 AM
SENT> ZZZ:1:FMZZZ:ID1 234:PWAAAA:VR10 0:\0
RCVD> ACASHTESTSX:\0
RCVD> ZZZ:1:FMZZZ:SW2 4657:CNUS:TO480 :TX113748:DX050 12004:DEOCX OPR
Is there any way I can manage this? Or something that would prevent
this from happening?
Thanks!
- Brian
Here is my test code:
using System;
using System.Net;
using System.Net.Sock ets;
namespace UnitTest
{
/// <summary>
/// Summary description for SocketTest.
/// </summary>
public class SocketTest
{
public SocketTest()
{
}
protected Socket _socket = null;
public class SocketPacket
{
public byte[] Buffer = new Byte[100];
public Socket Socket;
public SocketPacket(So cket socket)
{
Socket = socket;
}
}
public void Stop()
{
_socket.Shutdow n(SocketShutdow n.Both);
_socket.Close() ;
}
public void Start(string ipAddress, int port)
{
// Create socket and connect
_socket = new Socket(AddressF amily.InterNetw ork,SocketType. Stream,
ProtocolType.Tc p);
IPEndPoint endPoint = new IPEndPoint(IPAd dress.Parse(ipA ddress),
port);
_socket.Connect (endPoint);
System.IO.Strea mWriter sw;
sw = System.IO.File. AppendText("C:\ \Connection.log ");
sw.WriteLine("C onnection at " + DateTime.Now.To String());
sw.Close();
// set up a bunch of receive packets
for (int i=1;i<10;i++)
{
SocketPacket packet = new SocketPacket(_s ocket);
_socket.BeginRe ceive(
packet.Buffer, 0, packet.Buffer.L ength,
SocketFlags.Non e,
new AsyncCallback(E ndReceive),
packet
);
}
// send a message
SocketPacket packet2 = new SocketPacket(_s ocket);
packet2.Buffer = System.Text.Enc oding.ASCII.Get Bytes("FOL:1:FM FOL:IDONE-FOL:PWEXIT:VR10 0:\0");
WriteBufferToLo g("SENT> ", packet2.Buffer) ;
_socket.BeginSe nd(
packet2.Buffer, 0, packet2.Buffer. Length,
SocketFlags.Non e,
new AsyncCallback(E ndSend),
packet2
);
}
public void EndSend(IAsyncR esult asyncResult)
{
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState;
packet.Socket.E ndSend(asyncRes ult);
}
public void EndReceive(IAsy ncResult asyncResult)
{
// we seem to get EndReceive's while disconnecting
// is there a way to drop these before we shutdown
// so EndReceive doesn't get called?
if (_socket == null)
return;
if (!_socket.Conne cted)
return;
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState;
packet.Socket.E ndSend(asyncRes ult);
WriteBufferToLo g("RCVD> ", packet.Buffer);
// put packet back on receive queue
_socket.BeginRe ceive(
packet.Buffer, 0, packet.Buffer.L ength,
SocketFlags.Non e,
new AsyncCallback(E ndReceive),
packet
);
}
public void WriteBufferToLo g(string prefix, byte[] buffer)
{
System.IO.Strea mWriter sw;
sw = System.IO.File. AppendText("C:\ \Connection.log ");
sw.WriteLine(pr efix + GetString(buffe r));
sw.Close();
}
public string GetString(byte[] buffer)
{
string result = "";
int index = 0;
while (index < buffer.Length && buffer[index] > 0)
{
char[] chars = new char[buffer.Length + 1];
System.Text.Dec oder d = System.Text.Enc oding.ASCII.Get Decoder();
int len = d.GetChars(buff er, index, buffer.Length - index, chars,
0);
string str = new System.String(c hars);
int n = str.IndexOf("\0 ");
if (n >= 0)
str = str.Substring(0 , n);
index += str.Length + 1;
if (index < buffer.Length)
result += str + @"\0";
else
result += str;
}
return result;
}
}
} 4 7580
Hi,
You should not send new packet before others are sent.
Currenlty you call BeginSend multiple times, you can't do this.
You must send all packets with single send, if this isn't possible, you need
to wait before first send completes and calls callback method.
"Brian Rice" <ma**@brianrice .com> wrote in message
news:dc******** *************** ***@posting.goo gle.com... 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:ID1 234:PWAAAA:VR10 0:\0 RCVD> ZZZ:1:FMZZZ:SW2 4657:CNUS:TO480 :TX113731:DX050 12004:DEOCX OPR RCVD> ACASHTESTSX:\0 Connection at 5/1/2004 11:39:32 AM SENT> ZZZ:1:FMZZZ:ID1 234:PWAAAA:VR10 0:\0 RCVD> ACASHTESTSX:\0 RCVD> ZZZ:1:FMZZZ:SW2 4657:CNUS:TO480 :TX113748:DX050 12004:DEOCX OPR
Is there any way I can manage this? Or something that would prevent this from happening?
Thanks!
- Brian
Here is my test code:
using System; using System.Net; using System.Net.Sock ets;
namespace UnitTest { /// <summary> /// Summary description for SocketTest. /// </summary> public class SocketTest { public SocketTest() { }
protected Socket _socket = null;
public class SocketPacket { public byte[] Buffer = new Byte[100]; public Socket Socket;
public SocketPacket(So cket socket) { Socket = socket; } }
public void Stop() { _socket.Shutdow n(SocketShutdow n.Both); _socket.Close() ; }
public void Start(string ipAddress, int port) { // Create socket and connect
_socket = new Socket(AddressF amily.InterNetw ork,SocketType. Stream, ProtocolType.Tc p);
IPEndPoint endPoint = new IPEndPoint(IPAd dress.Parse(ipA ddress), port);
_socket.Connect (endPoint);
System.IO.Strea mWriter sw; sw = System.IO.File. AppendText("C:\ \Connection.log "); sw.WriteLine("C onnection at " + DateTime.Now.To String()); sw.Close();
// set up a bunch of receive packets for (int i=1;i<10;i++) { SocketPacket packet = new SocketPacket(_s ocket); _socket.BeginRe ceive( packet.Buffer, 0, packet.Buffer.L ength, SocketFlags.Non e, new AsyncCallback(E ndReceive), packet ); }
// send a message SocketPacket packet2 = new SocketPacket(_s ocket); packet2.Buffer =
System.Text.Enc oding.ASCII.Get Bytes("FOL:1:FM FOL:IDONE-FOL:PWEXIT:VR10 0:\0")
; WriteBufferToLo g("SENT> ", packet2.Buffer) ; _socket.BeginSe nd( packet2.Buffer, 0, packet2.Buffer. Length, SocketFlags.Non e, new AsyncCallback(E ndSend), packet2 ); }
public void EndSend(IAsyncR esult asyncResult) { SocketPacket packet = (SocketPacket)a syncResult.Asyn cState; packet.Socket.E ndSend(asyncRes ult); }
public void EndReceive(IAsy ncResult asyncResult) { // we seem to get EndReceive's while disconnecting // is there a way to drop these before we shutdown // so EndReceive doesn't get called? if (_socket == null) return; if (!_socket.Conne cted) return;
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState;
packet.Socket.E ndSend(asyncRes ult);
WriteBufferToLo g("RCVD> ", packet.Buffer);
// put packet back on receive queue _socket.BeginRe ceive( packet.Buffer, 0, packet.Buffer.L ength, SocketFlags.Non e, new AsyncCallback(E ndReceive), packet ); }
public void WriteBufferToLo g(string prefix, byte[] buffer) { System.IO.Strea mWriter sw; sw = System.IO.File. AppendText("C:\ \Connection.log "); sw.WriteLine(pr efix + GetString(buffe r)); sw.Close(); }
public string GetString(byte[] buffer) { string result = "";
int index = 0; while (index < buffer.Length && buffer[index] > 0) { char[] chars = new char[buffer.Length + 1]; System.Text.Dec oder d = System.Text.Enc oding.ASCII.Get Decoder(); int len = d.GetChars(buff er, index, buffer.Length - index, chars, 0); string str = new System.String(c hars);
int n = str.IndexOf("\0 "); if (n >= 0) str = str.Substring(0 , n);
index += str.Length + 1;
if (index < buffer.Length) result += str + @"\0"; else result += str; }
return result; } } }
> You should not send new packet before others are sent. Currenlty you call BeginSend multiple times, you can't do this. You must send all packets with single send, if this isn't possible, you need to wait before first send completes and calls callback method.
In this example I am only doing ONE send.
BTW: If I up my buffer to, say, 512 bytes then my log looks like this:
Connection at 5/1/2004 1:39:33 PM
SENT> ZZZ:1:FMZZZ:ID1 234:PWAAAA:VR10 0:\0
RCVD> ZZZ:1:FMZZZ:SW2 4657:CNUS:TO480 :TX113731:DX050 12004:DEOCX
OPRACASHTESTSX: \0
But, of course the problem is that I can get really large packets and
still have the same problem. Has anybody else experienced this issue
of packets coming back on different threads and therefore not
neccesarilly being in the right order?
Ok... I think you meant I was doing multiple BeginReceive's. ..
because, now, when I only do one BeginReceive and then do another
*only* after I have completed an EndReceive it works. So, my thinking
of having a pool of "BeginRecei ve" packets is probably fine as long as
I don't care about the order that I get them... but I do care so the
pool idea is bad for me.
Here is my revised code... and it works really well.
using System;
using System.Net;
using System.Net.Sock ets;
namespace UnitTest
{
/// <summary>
/// Summary description for SocketTest.
/// </summary>
public class SocketTest
{
public SocketTest()
{
}
protected Socket _socket = null;
public class SocketPacket
{
public byte[] Buffer = new Byte[30];
public Socket Socket;
public SocketPacket(So cket socket)
{
Socket = socket;
}
}
public void Stop()
{
_socket.Shutdow n(SocketShutdow n.Both);
_socket.Close() ;
}
public void Start(string ipAddress, int port)
{
// Create socket and connect
_socket = new Socket(AddressF amily.InterNetw ork,SocketType. Stream,
ProtocolType.Tc p);
IPEndPoint endPoint = new IPEndPoint(IPAd dress.Parse(ipA ddress),
port);
_socket.Connect (endPoint);
System.IO.Strea mWriter sw;
sw = System.IO.File. AppendText("C:\ \Connection.log ");
sw.WriteLine("C onnection at " + DateTime.Now.To String());
sw.Close();
// set up one receive packet
SocketPacket packet = new SocketPacket(_s ocket);
_socket.BeginRe ceive(
packet.Buffer, 0, packet.Buffer.L ength,
SocketFlags.Non e,
new AsyncCallback(E ndReceive),
packet
);
// send a message
SocketPacket packet2 = new SocketPacket(_s ocket);
packet2.Buffer = System.Text.Enc oding.ASCII.Get Bytes("FOL:1:FM FOL:IDONE-FOL:PWEXIT:VR10 0:\0");
WriteBufferToLo g("SENT> ", packet2.Buffer) ;
_socket.BeginSe nd(
packet2.Buffer, 0, packet2.Buffer. Length,
SocketFlags.Non e,
new AsyncCallback(E ndSend),
packet2
);
}
public void EndSend(IAsyncR esult asyncResult)
{
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState;
packet.Socket.E ndSend(asyncRes ult);
}
public void EndReceive(IAsy ncResult asyncResult)
{
// we seem to get EndReceive's while disconnecting
if (_socket == null)
return;
if (!_socket.Conne cted)
return;
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState;
packet.Socket.E ndSend(asyncRes ult);
WriteBufferToLo g("RCVD> ", packet.Buffer);
// put packet back on receive queue
packet.Buffer.I nitialize();
for (int i=0;i<packet.Bu ffer.Length;i++ )
packet.Buffer[i] = 0;
_socket.BeginRe ceive(
packet.Buffer, 0, packet.Buffer.L ength,
SocketFlags.Non e,
new AsyncCallback(E ndReceive),
packet
);
}
public void WriteBufferToLo g(string prefix, byte[] buffer)
{
System.IO.Strea mWriter sw;
sw = System.IO.File. AppendText("C:\ \Connection.log ");
sw.WriteLine(pr efix + GetString(buffe r));
sw.Close();
}
public string GetString(byte[] buffer)
{
string result = "";
int index = 0;
while (index < buffer.Length && buffer[index] > 0)
{
char[] chars = new char[buffer.Length + 1];
System.Text.Dec oder d = System.Text.Enc oding.ASCII.Get Decoder();
int len = d.GetChars(buff er, index, buffer.Length - index, chars,
0);
string str = new System.String(c hars);
int n = str.IndexOf("\0 ");
if (n >= 0)
str = str.Substring(0 , n);
index += str.Length + 1;
if (index < buffer.Length)
result += str + @"\0";
else
result += str;
}
return result;
}
}
} Ok... I think you meant I was doing multiple BeginReceive's. ..
Yes.
"Brian Rice" <ma**@brianrice .com> wrote in message
news:dc******** *************** **@posting.goog le.com... Ok... I think you meant I was doing multiple BeginReceive's. .. because, now, when I only do one BeginReceive and then do another *only* after I have completed an EndReceive it works. So, my thinking of having a pool of "BeginRecei ve" packets is probably fine as long as I don't care about the order that I get them... but I do care so the pool idea is bad for me.
Here is my revised code... and it works really well.
using System; using System.Net; using System.Net.Sock ets;
namespace UnitTest { /// <summary> /// Summary description for SocketTest. /// </summary> public class SocketTest { public SocketTest() { }
protected Socket _socket = null;
public class SocketPacket { public byte[] Buffer = new Byte[30]; public Socket Socket;
public SocketPacket(So cket socket) { Socket = socket; } }
public void Stop() { _socket.Shutdow n(SocketShutdow n.Both); _socket.Close() ; }
public void Start(string ipAddress, int port) { // Create socket and connect
_socket = new Socket(AddressF amily.InterNetw ork,SocketType. Stream, ProtocolType.Tc p);
IPEndPoint endPoint = new IPEndPoint(IPAd dress.Parse(ipA ddress), port);
_socket.Connect (endPoint);
System.IO.Strea mWriter sw; sw = System.IO.File. AppendText("C:\ \Connection.log "); sw.WriteLine("C onnection at " + DateTime.Now.To String()); sw.Close();
// set up one receive packet SocketPacket packet = new SocketPacket(_s ocket); _socket.BeginRe ceive( packet.Buffer, 0, packet.Buffer.L ength, SocketFlags.Non e, new AsyncCallback(E ndReceive), packet );
// send a message SocketPacket packet2 = new SocketPacket(_s ocket); packet2.Buffer =
System.Text.Enc oding.ASCII.Get Bytes("FOL:1:FM FOL:IDONE-FOL:PWEXIT:VR10 0:\0")
; WriteBufferToLo g("SENT> ", packet2.Buffer) ; _socket.BeginSe nd( packet2.Buffer, 0, packet2.Buffer. Length, SocketFlags.Non e, new AsyncCallback(E ndSend), packet2 ); }
public void EndSend(IAsyncR esult asyncResult) { SocketPacket packet = (SocketPacket)a syncResult.Asyn cState; packet.Socket.E ndSend(asyncRes ult); }
public void EndReceive(IAsy ncResult asyncResult) { // we seem to get EndReceive's while disconnecting if (_socket == null) return; if (!_socket.Conne cted) return;
SocketPacket packet = (SocketPacket)a syncResult.Asyn cState; packet.Socket.E ndSend(asyncRes ult);
WriteBufferToLo g("RCVD> ", packet.Buffer);
// put packet back on receive queue packet.Buffer.I nitialize(); for (int i=0;i<packet.Bu ffer.Length;i++ ) packet.Buffer[i] = 0; _socket.BeginRe ceive( packet.Buffer, 0, packet.Buffer.L ength, SocketFlags.Non e, new AsyncCallback(E ndReceive), packet ); }
public void WriteBufferToLo g(string prefix, byte[] buffer) { System.IO.Strea mWriter sw; sw = System.IO.File. AppendText("C:\ \Connection.log "); sw.WriteLine(pr efix + GetString(buffe r)); sw.Close(); }
public string GetString(byte[] buffer) { string result = "";
int index = 0; while (index < buffer.Length && buffer[index] > 0) { char[] chars = new char[buffer.Length + 1]; System.Text.Dec oder d = System.Text.Enc oding.ASCII.Get Decoder(); int len = d.GetChars(buff er, index, buffer.Length - index, chars, 0); string str = new System.String(c hars);
int n = str.IndexOf("\0 "); if (n >= 0) str = str.Substring(0 , n);
index += str.Length + 1;
if (index < buffer.Length) result += str + @"\0"; else result += str; }
return result; } } } This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Zunbeltz Izaola |
last post by:
Hi,
I have the following problem.
I'm developing a GUI program (wxPython). This program has to comunicate
(TCP) whit other program that controls a laboratory machine to do a
measurement. I have a dialog box, wiht two buttoms "Start measurement" and
"Stop". "Start" executes a function that do the measurement in the
following way.
|
by: Lynne |
last post by:
I am using the C# asynchronous socket functionality for a server, and
it appears to work fine if I just receive data and echo it back to the
client. The problem occurs when I try to handle sending data
independent of a receive. The send happens just fine, but when I
receive the next set of data from the client (in a size, size, data
set of...
|
by: Steve - DND |
last post by:
I'm trying to determine if I need to make my application multi-threaded, or
if it can be done with asynchronous programming. I realize that asynch calls
do create a new thread in the background, but when they come back, they
return to the thread that launched them, is that correct? If I go
multi-threaded, then I just need to spawn a new thread...
|
by: Richard |
last post by:
Hi,
I'm suffering a socket race condition - I think. The code works fine at
full speed on a single CPU machine. However when I run full speed on a 2
Zeon machine the socket drops data on an asynchronous receive. If I slow a
connected client down by step debugging or putting Thread.Sleep() calls
between sends then the code works on the...
|
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"...
| |
by: Macca |
last post by:
Hi,
I am writing an asychronous socket server to handle 20+ simulataneous
connections.
I have used the example in MSDN as a base. The code is shown at end of
question.
Each connection has a number of different types of data coming in. I have a
databuffer for each type of data coming in.
|
by: Engineerik |
last post by:
I am trying to create a socket server which will listen for connections from
multiple clients and call subroutines in a Fortran DLL and pass the results
back to the client. The asynchronous socket client and asynchronous socket
server example code provided in the .NET framework developers guide is a
great start but I have not dealt with...
|
by: darthghandi |
last post by:
I am trying to create a server application using asynchronous
sockets. I run into a problem when I try to connect to my server
using a non-.net program. I can establish the connection, and send
some packets in response to the programs first message, but when I
receive a response back, it's the last packet I sent. After that
packet, I...
|
by: Nicolas Le Gland |
last post by:
Hello everyone here.
This is my first post in this newsgroup, I hope I won't be to much
off-topic. Feel free to redirect me to any better group.
I am getting strange timing issues when failing to asynchronously connect
sockets on closed or filtered ports, but I'm quite unsure if this is a PHP
issue or my misunderstanding, as it seems...
|
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...
|
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. ...
| |
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: 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...
| |