【发布时间】:2014-05-01 06:05:29
【问题描述】:
我正在编写一个客户端应用程序(Windows 服务),它定期从服务器读取数据并将数据写入服务器。如果客户端接收到的帧被理解,服务器被配置为总是回复客户端。我有以下发送和接收的方法:
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 打开吗?该函数被定期调用。
【问题讨论】:
标签: c# service tcp tcpclient networkstream