C# 为什么打开和关闭套接字会导致数据丢失?

C# 为什么打开和关闭套接字会导致数据丢失?,c#,sockets,tcpclient,C#,Sockets,Tcpclient,我不能共享服务器代码,因为它托管在加密设备中,我也没有访问权限,也没有文档记录 在这个场景中,我正在通过循环中的套接字向加密设备发送一个命令。加密设备处理套接字命令,并在成功后将该命令转发给打印机 情景1 for (int i = 1; i <= 10; i++) { // Step 1. Initialize TcpClient stream m_client = new TcpClient(); m_client.Client.ExclusiveAddre

我不能共享服务器代码,因为它托管在加密设备中,我也没有访问权限,也没有文档记录

在这个场景中,我正在通过循环中的套接字向加密设备发送一个命令。加密设备处理套接字命令,并在成功后将该命令转发给打印机

情景1

for (int i = 1; i <= 10; i++)
{
     // Step 1. Initialize TcpClient stream
     m_client = new TcpClient();
     m_client.Client.ExclusiveAddressUse = false;
     m_client.ReceiveTimeout = 20000;
     m_client.SendTimeout = 20000;
     m_client.Connect(SrmIp, Port); 
     m_stream = new SslStream(m_client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
     m_stream.AuthenticateAsClient("MEV", null, SslProtocols.Tls, false);


     // Step 2. Write data command
     m_stream.Write(aTaille, 0, aTaille.Length);
     m_stream.Write(SrmCheckData, 0, SrmCheckData.Length);

     // Step 3. Receive the status response from the encryption device
     int status = ReceiveReturnCode(true);
     if (status != 2)
          throw new Exception("Encryption Error");

     // Step 4.Close the stream
     m_stream.Close();
}

for(int i=1;i如果在
m_stream.Write(SrmCheckData,0,SrmCheckData.Length)之后调用
m_stream.Flush()
?@JamesKPolk网络流没有缓冲,ergo flush什么都不做。但是我不确定SSLStream是否是一个特例,所以这确实值得一试。可能是因为有些数据包被延迟或重新发送,而您过早关闭套接字?这是一个半相关的注意事项,这就是为什么在处置时使用
HttpClient
,套接字仍将保持打开状态大约2分钟,特别是出于这个原因。@TheGeneral:谢谢,我对.NET不是很在行,我对Java比较熟悉。我想这可能是缓冲问题或是Nagle算法的影响。为什么总是连接TcpClient?是TCP,对吗?连接一次,发送多次,然后在离开之前关闭。