Я пишу клиентское приложение (службу Windows), которое регулярно считывает данные и записывает данные на сервер. Сервер настроен так, чтобы всегда отвечать клиенту, если он понял. У меня есть следующий метод для отправки и получения:Когда закрывать tcpclient и networkstream
public byte[] Sendmessage(byte[] arrbMessage)
{
byte[] arrbDataInput; // byteArray for received data
try
{
_oStream = _oClient.GetStream(); // try to get a networkstream
}
catch (InvalidOperationException e)
{
Connect(); // if this fails, tcpclient is probably disconnected, reconnect client and networstream
}
if (_oClient.Connected)
try
{ // Send the arrbMessage to the connected TcpServer.
string sKey = "123456789ABC";
byte[] arrbMessageEncrypted = EncryptedFrame(arrbMessage, sKey);
if (_oStream.CanWrite) // if stream is available for writing
{
_oStream.Write(arrbMessageEncrypted, 0, arrbMessageEncrypted.Length); //send message
_oStream.Flush(); //Clear stream
}
// Receive the TcpServer.response.
if (_oStream.CanRead) // if stream is available for reading
{
arrbDataInput = new byte[256]; // set inputbuffer to 256
//_oClient.NoDelay = true; // don't wait if nothing is received
// Read the first batch of the TcpServer response bytes.
_oStream.ReadTimeout = 2000;
Int32 bytes = _oStream.Read(arrbDataInput, 0, arrbDataInput.Length); //read out data, put datalength in "bytes"
Array.Resize(ref arrbDataInput, bytes); // resize array to length of received data
_oStream.Close(); // close the network stream
if (arrbDataInput.Length > 0)
{
byte[] arrbMessageDecrypted = DecryptedFrame(arrbDataInput, sKey);
if (CheckBusy(arrbMessageDecrypted))
throw new ArgumentNullException();
return arrbMessageDecrypted;
}
return null; // return the received data
}
}
catch (ArgumentNullException e)
{
return Sendmessage(arrbMessage);
}
catch (SocketException e)
{
}
catch (System.IO.IOException e)
{
while (!_oClient.Connected)
{
Connect();
}
}
else
{
while (!_oClient.Connected)
{
Connect();
}
}
return null;
}
У меня было много трудностей, оставляя поток открытым, поэтому на данный момент мы закрываем его каждый раз после отправки и получения данных. Должен ли я оставить поток и tcpclient открытым? функция регулярно вызывается.