Skip to content

Udp sockets

ninja

Asked May 15, 2008, 11:19 AM EDT1 answer
Share
LinkedInX
I need to send a large number of UDP pakets ~ 8000/s at 540bytes(header included). The problem is only capures 197 frames (the buffer size) and then my computer almost freezes. Any ideeas what's to do?
Here is the source code internal void OnReceive(IAsyncResult ar) { serverSocket.EndReceive(ar); frames++ serverSocket.BeginReceive(byteData, 0, 540, SocketFlags.None, new AsyncCallback(OnReceive), null); } why the hell can't i insert a linefeed>

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I don`t really see you beginning a new asynchronous receive, here is some receive callback sample I made:

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;

    namespace ConsoleApplication1
    {
        class Program
        {

            static UdpClient udp;
            static IPEndPoint ipe;

            public static void ReceiveCallback(IAsyncResult ar)
            {
                byte[] recvBytes = udp.EndReceive(ar, ref ipe);
                Console.WriteLine("{0} received {1} bytes from {2}:{3}",
                    DateTime.Now.ToString(),
                    recvBytes.Length,
                    ipe.Address,
                    ipe.Port);
                string str = ASCIIEncoding.ASCII.GetString(recvBytes);
                Console.WriteLine("\"{0}\"", str);
                if (ar.IsCompleted)
                {
                    ar = udp.BeginReceive(ReceiveCallback, udp);
                }
            }

            static void Main(string[] args)
            {
                ipe = new IPEndPoint(IPAddress.Loopback, 1234);
                udp = new UdpClient(ipe);
                udp.Client.ReceiveBufferSize = 8192;
                udp.Client.SendBufferSize = 8192;
                Console.WriteLine("{0} started listening on localhost:1234",
                    DateTime.Now.ToString());
                IAsyncResult ia = udp.BeginReceive(ReceiveCallback, udp);
                while (!Console.KeyAvailable)
                {
                    Thread.Sleep(1);
                }
                if (ia != null && ia.AsyncState != null && !ia.IsCompleted)
                {
                    udp.EndReceive(ia, ref ipe);
                }
                udp.Close();
                Console.WriteLine();
                Console.WriteLine("{0} all done", DateTime.Now.ToString());
                Console.ReadKey(true);
            }
        }
    }


    maybe it helps, note that when an asynchronous receive is completed you need to begin a new one, and so on until the end :)
    0