Darqer
Darqer

Reputation: 2887

c# tcp communication, sends empty data on GetStream

When I'm using this piece of code, it sends an empty byte array to my receiver. Why, I do not write anything to the stream I only obtain it. What can I do in order to prevent it ?

public void Send()
{
  TcpClient client = new TcpClient();
  IPEndPoint serverEndPoint = new IPEndPoint( IPAddress.Parse( ip ), port );
  client.Connect( serverEndPoint );

  NetworkStream clientStream = client.GetStream();

  clientStream.Close();
  client.Close();
}



  private TcpListener tcpListener;
  private Thread listenThread;

  public void Receiver()
  {
   this.tcpListener = new TcpListener( IPAddress.Any, port );
   this.listenThread = new Thread( new ThreadStart( ListenForClients ) );
   this.listenThread.Start();
  }

  private void ListenForClients()
  {
   this.tcpListener.Start();

   while ( true )
   {
    //blocks until a client has connected to the server
    TcpClient client = this.tcpListener.AcceptTcpClient();

    Thread clientThread = new Thread( new ParameterizedThreadStart( HandleClientComm ));
    clientThread.Start( client );
    }   
  }

  private void HandleClientComm( object client )
  {
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();

    tcpClient.Close();
  }

Upvotes: 1

Views: 578

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503489

It's not clear what you mean by "send empty byte array" - but look at this code:

NetworkStream clientStream = client.GetStream();
clientStream.Close();

That will close the connection. It's not clear what your code is meant to do, but it seems unlikely that you really want to accept a connection, only to immediately close it.

You do the same thing in HandleClientComm, this time by closing the TcpClient.

Upvotes: 3

Related Questions