Connect Button TCPclient, help

Hi there.
I created 3 buttons which have different tasks. the first one is “connect”, the second one “send msg” and the third one “Disconnect”. Here i display the first two buttons.

My problems is that the SendMSg Button always tells me IOException:Not connected.

This only happens if i split the functions on two buttons. If the buttons are combined, and the Connect button connects and sends the massage after connecting, i receive the message on my server (which is a different programm).
What do i do wrong or how can i call the connect button in my message button?

Connect

public class ConnectToServer : MonoBehaviour
{
    TcpClient client = new TcpClient();
   
    public void onClick()
    {
        client.Connect("127.0.0.1", 30005);
        NetworkStream stream = client.GetStream();
        client.GetStream();
    }

}

SendMsg

public class SendMsgToPlant : MonoBehaviour
{
    Byte[] data = System.Text.Encoding.ASCII.GetBytes("asdasd message");
    TcpClient client = new TcpClient();

    public void SendMsg()
    {
        NetworkStream stream = client.GetStream();

        if (client.Connected)
            stream.Write(data, 0, data.Length);
    }
}

The problem is you have two different TcpClients. The one in the ConnectToServer class has nothing to do with the other in the SendMsgToPlant class. Those are two separate objects and so the first client gets connected on click, but it doesn’t make the second client connect.

Why this works when you have everything in one class is because there is only one client. If you want to keep the code separated like it is now, you’ll have to make a decision on how to share the client between your components.

You can create a third class which will own the client, and then reference the instance of this class in both ConnectToServer and SendMsgToPlant:

public class TcpClientSource : MonoBehaviour
{
    public TcpClient Client { get { return m_client; } private set { m_client = value; } }
    TcpClient m_client = new TcpClient ();
}

public class SendMsgToPlant : MonoBehaviour
{
    public TcpClientSource ClientSource;
    TcpClient client;

    void Start ()
    {
        client = ClientSource.Client;
    }
    
    // Implementation
}

You could also inject the client to your classes, or use a singleton. There are some more options but those 3 methods should suffice.

thank you very much.
it worked like a charm