C# TCP Listener from a backgroundworker

0

I have this very simple code snippet in which a simple TCP listener is created.

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

namespace TCPListenerTest
{
    class Program
    {
        static void Main(string[] args)
        {

            IPAddress localAddr = IPAddress.Any;
            TcpListener server = null;
            bool done = false;

            server = new TcpListener(localAddr, 5081);
            server.Start();
            while (!done)
            {
                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();

                //Connected!!
                Console.WriteLine("Connected");
                client.Close();
                done = true;
            }
            Console.WriteLine("Done");
            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
    }
}

When I run this code in a Console Application or in a Windows Form everything is fine, i.e. The listener accepts a connection from a client.

When I place this code inside a backgroundworker_DoWork, the client is unable to connect.

I wonder whether there is some issue when usingTCPListener from Backgroundworker.

EDIT: You were right, the TCP Listener works fine inside the background worker.

The code below works fine. It sends a command (http:///config.cgi?F=8&A=) to an embedded board to start a file transfer. The board acts as a client. It first request the total number of bytes and the number of packets it will receive. Successively the board sends a request for each packet until the full transfer is done.

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace TCPListenerBackgroundWorkerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        String HostIP = "192.168.0.14";
        String BoardIP = "192.168.0.144";
        String pacchettozzoDest = "Italiano.bin";

        void flasherase()
        {
            byte[] stream;

            String cgireq = String.Format("http://{0}/config.cgi?F=8&A={1}", BoardIP, HostIP);          
            try
            {
                WebClient wClient = new WebClient();
                stream = wClient.DownloadData(cgireq);
            }
            catch (Exception ex)
            {
            }
        }


        void updateProcess()
        {
            try
            {
                int updateProg;
                int readBytes;
                int n1 = 0;
                int n2 = 0;
                int PAYLOADSIZE = 1000;
                int HEADERSIZE = 8;
                UInt32 UpdateLength = 0;
                int UpdatePackets = 0;
                bool updateDone = false;
                System.IO.FileStream messFile;
                FileStream sr;

                TcpListener server = null;
                
                messFile = new FileStream(pacchettozzoDest, FileMode.Open, FileAccess.Read);
                UpdateLength = (UInt32)messFile.Length;
                UpdatePackets = (int)(UpdateLength / PAYLOADSIZE);
                messFile.Close();
                if ((UpdatePackets * PAYLOADSIZE) < UpdateLength)
                    UpdatePackets++;

                server = new TcpListener(IPAddress.Any, 5081);
                //Allocate Buffer fore reading data
                byte[] TXbuffer = new byte[256];
                byte[] RXbuffer = new byte[1024];
                // Start listening for client requests.
                server.Start();

                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                //Connected!!
                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                while (!updateDone)
                {
                    

                    readBytes = stream.Read(RXbuffer, 0, RXbuffer.Length);

                    if (readBytes >= HEADERSIZE)
                    {
                        if (RXbuffer[1] == 0xBE && RXbuffer[0] == 0xEA && RXbuffer[7] == 0xFC && RXbuffer[6] == 0xCF)
                        {
                            n1 = (RXbuffer[3] << 8) + RXbuffer[2];
                            n2 = (RXbuffer[5] << 8) + RXbuffer[4];
                            // First Packet
                            if (0 == n1 && 0 == n2)
                            {
                                byte[] bufferTX = new byte[HEADERSIZE];
                                bufferTX[1] = 0xBE; bufferTX[0] = 0xEA;
                                bufferTX[3] = (byte)((UpdatePackets & 0xFF00) >> 8);
                                bufferTX[2] = (byte)((UpdatePackets & 0xFF));

                                bufferTX[4] = (byte)((UpdateLength & 0x000000FF));
                                bufferTX[5] = (byte)((UpdateLength & 0x0000FF00) >> 8);
                                bufferTX[6] = (byte)((UpdateLength & 0x00FF0000) >> 16);
                                bufferTX[7] = (byte)((UpdateLength & 0xFF000000) >> 24);

                                stream.Write(bufferTX, 0, 8);
                                updateProg = 0;
                            }
                            else if (n1 > 0 && 0 == n2)
                            {
                                byte[] bufferTX = new byte[PAYLOADSIZE + HEADERSIZE];

                                bufferTX[0] = 0xEA;
                                bufferTX[1] = 0xBE;

                                bufferTX[2] = (byte)((n1 & 0xFF));
                                bufferTX[3] = (byte)((n1 & 0xFF00) >> 8);

                                updateProg = (n1 * 100) / UpdatePackets;

                                sr = File.OpenRead(pacchettozzoDest);
                                sr.Seek((n1 - 1) * PAYLOADSIZE, SeekOrigin.Begin);

                                int readB = 0;
                                int PaySize = 0;
                                for (int p = 0; p < PAYLOADSIZE; p++)
                                {
                                    readB = sr.ReadByte();
                                    if (readB != -1)
                                    {
                                        bufferTX[p + 6] = (byte)readB;
                                        PaySize++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                bufferTX[4] = (byte)((PaySize & 0xFF));
                                bufferTX[5] = (byte)((PaySize & 0xFF00) >> 8);

                                bufferTX[6 + PAYLOADSIZE] = 0xCF;
                                bufferTX[6 + PAYLOADSIZE + 1] = 0xFC;
                                sr.Close();

                                stream.Write(bufferTX, 0, (PAYLOADSIZE + HEADERSIZE));
                                updateProg = 0;
                            }
                            //End
                            else if ((0xFFFF == n1) && (0xFFFF == n2))
                            {
                                // Shutdown and end connection
                                client.Close();
                                updateProg = 100;
                                updateDone = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            IPAddress localAddr = IPAddress.Any;
            TcpListener server = null;
            bool done = false;


            flasherase();

            updateProcess();

            MessageBox.Show("Done");                        
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("BKGRW Completed");
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }
    }
}
c#
backgroundworker
tcplistener
asked on Stack Overflow Mar 31, 2021 by peregrinus • edited Apr 1, 2021 by peregrinus

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0