Socket.BeginReceiveFrom gives multiple callbacks
- From: Scewbedew <Scewbedew@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 10 Jul 2006 14:04:02 -0700
I'm trying to write a UDP client that receives broadcast messages. I have a
server broadcasting at UDP port 12345 and the client is listening for
broadcasts at that port.
Initially, it seems as if everything works, but a closer look reveals that I
get 2 strange problems:
1. For each individual server broadcast, I get the MessageReceiveCallback
function called 3 times (network trafic investigated with a sniffer to
certify that is is a single UDP packet). Each time I get the same complete
UDP packet in the callback function. The deserialized SOAP information is
correctly formatted and everything seems to be OK.
2. After 2-3 broadcasts (i.e. 6-9 calls to the callback function), I get an
"InvalidOperationException" in the deserialize function. As far as I can
tell, all involved objects are still holding valid content, so I really don't
understand what the problem is.
I presume thatt the root cause of my problem is the multiple activation of
the callback function. Can anyone tell me why this happens?
Code:
public static partial class ClientService
{
public static Socket workSocket;
public static EndPoint bindEndPoint;
public static byte[] buffer = new byte[2000];
public static void InitializeUDPReceiver()
{
workSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
bindEndPoint = new IPEndPoint(IPAddress.Any, 12345);
workSocket.Bind(bindEndPoint);
workSocket.BeginReceiveFrom(buffer, 0, buffer.Length,
SocketFlags.None, ref bindEndPoint, new
AsyncCallback(MessageReceivedCallback), workSocket);
}
public static void MessageReceivedCallback(IAsyncResult result)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEndPoint = (EndPoint)sender;
int bytesRead = workSocket.EndReceiveFrom(result, ref
remoteEndPoint);
XmlTypeMapping myTypeMapping = (new
SoapReflectionImporter().ImportTypeMapping(typeof(SOAPData)));
XmlSerializer mySerializer = new XmlSerializer(myTypeMapping);
MemoryStream s = new MemoryStream(buffer);
SOAPData PublishedData = (SOAPData)mySerializer.Deserialize(s);
workSocket.BeginReceiveFrom(buffer, 0, buffer.Length,
SocketFlags.None, ref bindEndPoint, new
AsyncCallback(MessageReceivedCallback), workSocket);
}
public static void StopUDPReceiver()
{
workSocket.Close();
}
}
.
- Prev by Date: Re: Reading blocks of data from socket
- Next by Date: Re: Bluetooth Help required.
- Previous by thread: Reading blocks of data from socket
- Next by thread: Re: Multicast IP-Table Entries
- Index(es):
Relevant Pages
|
Loading