1

I finally got the program to work as I wanted is reading the data from the telnet port for every scan it triggers, but now the only problem I am getting is that is reading the data if I display it in the console but I need it display into my main display which will be a text box multiline, can you see why I am getting this

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

namespace BarcodeReceivingApp
{
    public partial class BarcodeReceivingForm : Form
    {
        public BarcodeReceivingForm()
        {
            InitializeComponent();

        }

        private Thread _readWriteThread;
        private TcpClient _client;
        private NetworkStream _networkStream;
        private void btn_ConnectToTelnetPort_Click(object sender, EventArgs e)
        {
            // connection tcp/ip
            const string hostname = "myipaddress";
            const int port = 23;
            ServerSocket(hostname, port);
            //Connect();

        }


        public void ServerSocket(string ip, int port)
        {
            try
            {
                _client = new TcpClient(ip, port);
                lbl_ConnectionMessage.Text = @"Connected to server.";
            }
            catch (SocketException)
            {
                MessageBox.Show(@"Failed to connect to server");
                return;
            }

            //Assign networkstream
            _networkStream = _client.GetStream();

            //start socket read/write thread
            _readWriteThread = new Thread(ReadWrite);
            _readWriteThread.Start();
        }

        private void ReadWrite()
        {
            var received = "";

            //Read first thing givent o us
            received = Read();
            //Console.WriteLine(received);
            txt_BarcodeDisplay.Text = received + Environment.NewLine;

            //txt_BarcodeDisplay.Text = recieved.ToString();


            //Set up connection loop
            while (true)
            {
                var command = btn_StopConnection.Text;
                if (command == "STOP1")
                    break;

                //write(command);
                received = Read();
                //Console.WriteLine(received);
                txt_BarcodeDisplay.Text += received + Environment.NewLine;
            }
            // possible method to end the port connection


        }

        public string Read()
        {
            byte[] data = new byte[1024];
            var received = "";

            var size = _networkStream.Read(data, 0, data.Length);
            received = Encoding.ASCII.GetString(data, 0, size);

            return received;
        }

        private void btn_StopConnection_Click(object sender, EventArgs e)
        {
            _networkStream.Close();
            _client.Close();
        }
    }
}

Here is I am adding the error and is coming from the ReadWrite method enter image description here

NewCoder
  • 109
  • 1
  • 8
  • 1
    read in a loop. – Daniel A. White Jan 17 '19 at 15:46
  • Possible duplicate of [Can a TCP c# client receive and send continuously/consecutively without sleep?](https://stackoverflow.com/questions/20694062/can-a-tcp-c-sharp-client-receive-and-send-continuously-consecutively-without-sle) – JuanR Jan 17 '19 at 15:55
  • how would you add it in a loop can I have an example based on my code – NewCoder Jan 17 '19 at 16:04
  • I don't think your connection is getting closed. It looks like you're doing your reading of the NetworkStream in your Connect function. Have you tried setting up a BackgroundWorker to manage the reads until you are ready to close the application? – Jim Fell Jan 17 '19 at 16:28
  • no I didn't how would I do that? – NewCoder Jan 17 '19 at 16:36

1 Answers1

1

So you'll have to have a loop somewhere to have your program keep checking the Stream. Usually the easiest was is with a Boolean indicator, so something list this:

Boolean openConnection = false;

This would need to be class level. Then inside your connect method, you loop and listen. Something like this.

NetworkStream ns = server.GetStream();
openConnection = True;
            Task.Factory.StartNew(() => 
                {
                    while (openConnection)
                    {
                        ns.Read(data, 0, data.Length);
                        var stringData = Encoding.ASCII.GetString(data, 0, 1024);
                        dataToAdd.Add(stringData);
                        foreach (var list in dataToAdd)
                        {
                            txt_BarcodeDisplay.Text += list + Environment.NewLine;
                        }
                        Thread.Sleep(2000);
                    }
                }
            );

So this is a lot to unpack, but basically you're saying, go read what comes in from the network, do it until the openConnection variable is set to false. Oh and since we don't want to peg the processor at 100%, Sleep the thread so we only check every 2 seconds.

This is a rough start, but I hope it will give you an idea of the direction you need to take this.

SamuelWarren
  • 1,449
  • 13
  • 28
  • I updated my request please take a look I have my program working but I am getting an error while displaying the data in my text box it works if I display it in the console but not on my textbox – NewCoder Jan 18 '19 at 13:14
  • It could be a problem with trying to update the UI on the wrong thread. You may need to either use the dispatcher to update the UI, or switch to a data binding to a collection and put the values in there... – SamuelWarren Apr 29 '19 at 19:33