0

I have a C# application which accepts data from a port(9100 ie, uses data when printer print something) and use it into an application. The problem is, sometimes it doesn't receiving data completely from printer and I have seen some questions regarding the difficulties in reading data at one time in TCP.

As I am not familiar with this, somebody please suggest me a better way to fix it.

Thanks in advance..

Here is my code

    TcpListener Listener = null;
    public Thread T = null;
    public FeederControlMonitor()
    {
        InitializeComponent();
    }

    private void FeederControlMonitor_Load(object sender, EventArgs e)
    {
        txtStatus.Text = "Feeder waiting for data...";
        ThreadStart Ts = new ThreadStart(StartReceiving);
        T = new Thread(Ts);
        T.Start();
    }
    public void StartReceiving()
    {
        ReceiveTCP(9100);
    }
    public void ReceiveTCP(int portN)
    {

        try
        {
            Listener = new TcpListener(IPAddress.Any, portN);
            Listener.Start();
        }
        catch (Exception ex)
        {
            File.WriteAllText(@"C:\\Drive\\ex.txt", ex.Message);
            Console.WriteLine(ex.Message);
        }
   try
        {

            while (true)
            {
                Socket client = Listener.AcceptSocket();
                var childSocketThread = new Thread(() =>
                {
                    byte[] data = new byte[20000];
                    int size = client.Receive(data);
                    ParseData(System.Text.Encoding.Default.GetString(data)); 
                  //Here some process will do with received data
                    client.Close();
                });
                childSocketThread.IsBackground = true;
                childSocketThread.Start();
                }
                 Listener.Stop();

        }
        catch (Exception ex)
        {
            File.WriteAllText(@"C:\\ex.txt", ex.Message);
        }
    }
Amjadh
  • 23
  • 4
  • Are you trying to communicate directly with a network printer? or are you trying to revceive data from another application? – Sebastian L May 08 '17 at 11:27
  • Printer server will send data to 9100 port of a computer IP Address, no special connection with printer. – Amjadh May 08 '17 at 11:28
  • can you add a small sample of complete and incomplete data? (before parsing) – Sebastian L May 08 '17 at 11:31
  • i thought the data would have a package size or something (obviously it doesn't) specific, since you mentioned you read some other questions regarding this matter. Have you tried this method (http://stackoverflow.com/questions/22465102/c-sharp-read-all-bytes) ? – Sebastian L May 08 '17 at 11:56

0 Answers0