Search code examples
c#tcptcpclient

Accessing one TCP connection from function. C#


I wanted to have a look into the TCP communication in C#. I already learned with Simple programs for receiving and sending over TCP. However I want to go one step further.

--EDIT: The simple programs all have one in common they open the TCP connection, send or receive and close the connection. If needed they start all over again. But this is not what I have in mind for my program. EDIT--

What I want to do:

I have a form with a button which establishes a connection to a server. (The server is given and is working correctly.) After the connection is established the user can send his commands via a button (bytes), and receives answers from the server displaying it in a label.

The kind of solution I came up with:

Since I wanted to make my program very flexible I created a class for handling the communication, separating it from the rest of the program code.

In this class CommunicationTCP I created three functions.

  1. Connecting to server
  2. Sending command
  3. receiving answer from server

This it what it looks like

.
.
.
using System.Net.Sockets;

//eventually tried declarations like
//TcpClient tcpclnt;
//NetworkStream tcpStream;

namespace MyProgram
{
  public partial class CommunicationTCP
  {
   public static void Connect()
   {
      TcpClient tcpclnt = new TcpClient();
      tcpclnt.Connect(ServerIP,ServerPORT);
   }

    public static void TCPSendData()
    {
      TcpClient tcpclnt = new TcpClient();
      NetworkStream netStream = tcpclnt.GetStream();
      byte[] sendbytes = Encoding.UTF8.GetBytes("COMMAND");
      netStream.Write(sendbytes, 0, sendbytes.Length);
    }

   public static void TCPGetData()
   {
    //not yet programmed.
   }
  }
}

The connect function is called when in Form_Load. The sending of the commands, like I said at the beginning, are send by the user over buttons.

Sadly the code above does not work because the tcpclnt is only available within their function. I tried different definitions of the function and declarations but with no success.

How can I change the program so that the tcp connection stays open and the commands are send?


Solution

  • You have to define your TcpClient as a class variable. That will solve your problems:

       TcpClient tcpclnt = new TcpClient();
    
       public static void Connect()
       {
          tcpclnt.Connect(ServerIP,ServerPORT);
       }
    
       public static void TCPSendData()
       {
         NetworkStream netStream = tcpclnt.GetStream();
         byte[] sendbytes = Encoding.UTF8.GetBytes("COMMAND");
         netStream.Write(sendbytes, 0, sendbytes.Length);
       }