Results 1 to 2 of 2

Thread: UDP - Receiving in background

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    UDP - Receiving in background

    Hi.

    It has been a REALLY long time so I would appreciate guidance here.
    I am using UDPClient to send and receive data.
    I have a simple example working but its lifetime is only for 1 time where I can send data and then receive and that's it.

    I want the application to be able to continuously receive data in the background (without blocking but processing any data coming through from a server).
    How would I do this? I HATE to use a while(true) approach and NO Thread.Sleep code either.

    I welcome any advice here to be able to continuously receive data in the background (and still be able to send data)

    Thanks!

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  2. #2
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,123

    Re: UDP - Receiving in background

    In my chatting program I've used an infinite loop for retrieving UDP packets and it is on a different thread.
    Code:
    private void WaitForPockets()
    {
        for (; ; )
        {
            try
            {
                byte[] data = client.Receive(ref receivePoint);
                string receivedMessage = System.Text.Encoding.ASCII.GetString(data);
    
                    NewMessageEventArgs e = new NewMessageEventArgs(Environment.NewLine + receivedMessage);
                //Raise event new message
                OnNewMessage(e);
            }
            catch (Exception exc)
            {
                Logger.LogException(exc);
                this.SetStatusBar("Error receiving message from " + Dns.GetHostEntry(receivePoint.Address.ToString()).HostName);
            }
        }
    }
    Code:
    try
    {
        client = new UdpClient(_port);
        receivePoint = new IPEndPoint(new IPAddress(0), 0);
        Thread readThread = new Thread(new ThreadStart(this.WaitForPockets));
        readThread.Start();
    }
    catch (Exception exc)
    {
        Logger.LogException(exc);
    }
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width