1

当我使用这段代码时,它会向我的接收器发送一个空字节数组。为什么,我不向流中写入任何内容,我只获得它。我能做些什么来防止它?

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();
  }
4

1 回答 1

3

目前尚不清楚“发送空字节数组”是什么意思 - 但看看这段代码:

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

这将关闭连接。目前尚不清楚您的代码是什么的,但您似乎不太可能真的想要接受连接,只是立即关闭它。

你在 中做同样的事情HandleClientComm,这次是通过关闭TcpClient.

于 2012-11-10T22:22:21.040 回答