Answer the question
In order to leave comments, you need to log in
Why does UdpClient.Send() sometimes throw an exception?
Good afternoon.
I have a simple program: random numbers are generated in an infinite loop, turned into bytes and sent via UdpClient.Send() to a broadcast group address. The problem is that about once every 10,000 calls to UdpClient.Send() throws a SocketException, code 10022, "Invalid argument received". I can't understand the reason for this behaviour.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Server
{
class Program
{
static int random_min;
static int random_max;
static Random random_gen = new Random();
static IPEndPoint endPoint;
static ulong sent_packages_count;
static ulong send_error_count;
static void Main(string[] args)
{
random_min = 0;
random_max = 100000;
int port = 8001;
endPoint = new IPEndPoint(IPAddress.Parse("235.5.5.11"), port);
Console.WriteLine("Remote address: " + endPoint.Address);
Console.WriteLine("Remote port: " + endPoint.Port);
Console.WriteLine("Random min: " + random_min);
Console.WriteLine("Random max: " + random_max);
Console.WriteLine("Starting sending!");
Thread senderThread = new Thread(new ThreadStart(SenderThreadProc));
senderThread.Start();
while (true)
{
Thread.Sleep(1000);
Console.WriteLine(DateTime.Now + " | Sent packages count: " + sent_packages_count+ " | Send error count:" + send_error_count);
}
}
private static void SenderThreadProc()
{
UdpClient sender = new UdpClient();
//int i = 0;
int value;
byte[] bytes;
try
{
while (true)
{
value = random_gen.Next(random_min, random_max);
bytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
try
{
// sender.Send иногда кидает исключение, причину не могу найти
sender.Send(bytes, bytes.Length, endPoint);
sent_packages_count++;
}
catch (SocketException ex)
{
send_error_count++;
//Console.WriteLine(ex.Message+ " value = " + value);
}
//Console.WriteLine(i+" "+ value);
//i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sender.Close();
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question