0

I'm trying to access the string of messageRecieved, which should pass to frmMain.Sort_Data(messageRecived);. However it's null once it hits here. The Console.WriteLine shows the correct data.

public class Client
{
    frm_main frmMain = new frm_main();
    public string ReturnDat;

    //for TCP communications
    TcpClient _client = null;

    //for sending/receiving data
    byte[] data;

    public Client(TcpClient client)
    {
        _client = client;
        //start reading data from the client in a separate thread
        data = new byte[_client.ReceiveBufferSize];
        _client.GetStream().BeginRead(
            data, 0, _client.ReceiveBufferSize, receiveMessage, null);
    }

    public void receiveMessage(IAsyncResult ar)
    {
        //read from client
        int bytesRead;

        lock (_client.GetStream())
        {
            bytesRead = _client.GetStream().EndRead(ar);
        }
        //if client has disconnected
        if (bytesRead < 1)
            return;
        else
        {
            //get the message sent
            string messageReceived =
                ASCIIEncoding.ASCII.GetString(data, 0, bytesRead);
            //Console.WriteLine(messageReceived);
            frmMain.Sort_Data(messageReceived);
            //ReturnDat = messageReceived;

        }
        //continue reading from client
        lock (_client.GetStream())
        {
            _client.GetStream().BeginRead(
                data, 0, _client.ReceiveBufferSize,
                receiveMessage, null);
        }
    }
}  

Below is the Sort_Data, which returns nothing when it's hit in the class.

Public void Sort_Data(string data)
{
    Messagebox.show(data);
}

Perhaps I'm missing something, or not calling something right?

  • You can only access UI elements from the UI thread. Read about BackgroundWorker and BeginInvoke. – xxbbcc Apr 04 '18 at 21:20
  • I may be missing something here - why are you locking on the stream? – xxbbcc Apr 04 '18 at 21:21
  • Locking seems to be the only way to get a listener to be stable on the device. Is there a simple way to pass that string instead of accessing the element? –  Apr 04 '18 at 21:27
  • I'm sorry, I missed the embedded bit on your question - my comments may be incorrect for that environment. – xxbbcc Apr 04 '18 at 21:29
  • Inside of the `Sort_Data` method, is `data` null? –  Apr 05 '18 at 14:07
  • Yes, the data returned when it reaches Sort_Data becomes null somehow. –  Apr 06 '18 at 14:37

0 Answers0