C#: How to Close a sslStream from other thread - c#

I am trying to let sslStream read asynchronously for 5 seconds. If the stream received nothing after 5 seconds, the stream will be closed.
The problem of current implementation is that closing the stream using this trick will emit an error on console saying: Cannot access a disposed object.
Is there any other way to achieve my goal without this error?
Here's my code:
private static async Task<string> ReadMessageAsync(SslStream pSslStream)
{
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
try
{
do
{
bytes = await pSslStream.ReadAsync(buffer, 0, buffer.Length)
.TimeoutAfter(TimeSpan.FromSeconds(5));
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
}
catch (TimeoutException)
{
Console.WriteLine("Timeout");
pSslStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return messageData.ToString();
}
public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
{
if (task != await Task.WhenAny(task, Task.Delay(timeout)))
{
throw new TimeoutException("Timeout");
}
return task.Result;
}
P/s: The extension method was from How do you catch CancellationToken.Register callback exceptions?

Related

How to handle Error in Async Network programming?

I have the following method :
private void ClientReadCallback(IAsyncResult asyncResult)
{
try
{
var networkStream = _client.GetStream();
var read = networkStream.EndRead(asyncResult);
if (read == 0)
{
Disconnected?.Invoke(this, new EventArgs());
}
byte[] buffer = asyncResult.AsyncState as byte[];
if (buffer != null)
{
byte[] data = new byte[read];
Buffer.BlockCopy(buffer, 0, data, 0, read);
networkStream.BeginRead(buffer, 0, buffer.Length, ClientReadCallback, buffer);
DataRead?.Invoke(this, new DataReadEventArgs(data));
}
}
catch (Exception ex)
{
GetLog().Error(ex);
ClientReadException?.Invoke(this, new ExceptionEventArgs(ex));
}
}
That triggers a : System.ObjectDisposedException: Cannot access a disposed object at some points.
My question is : in which situation does this happens? network issue? How to handle this properly ?
thanks

Code gets stuck while writing to a Network Stream

I am reading a .bin file and writing it into a Stream. Later, I am reading that stream object and then writing it into a Network Stream. Code is as following:
public async Task<bool> UploadFirmware(Stream _stream)
{
bool success = false;
try
{
_tcpclient = new TcpClient();
_tcpclient.Connect(_deviceip, port);
_stream.Seek(0, SeekOrigin.Begin);
m_NetworkStream = _tcpclient.GetStream();
byte[] buffer = new byte[1024];
m_ReadBuffer = new byte[1024];
int readcount = 0;
m_NetworkStream.BeginRead(m_ReadBuffer, 0, m_ReadBuffer.Length, new AsyncCallback(EndReceive), null);
await Task.Run(() =>
{
while ((readcount = _stream.Read(buffer, 0, buffer.Length)) > 0)
{
m_NetworkStream.Write(buffer, 0, readcount);
m_NetworkStream.Flush();
}
});
success = true;
}
catch (Exception ex)
{}
return success;
}
Normally, this code works fine, but sometimes on an IP Address, the code gets stuck at m_NetworkStream.Write(buffer, 0, readcount);. The thing is, I am updating the status in UI based on success value, but the code gets hanged at above mentioned line and doesn't come out at all. No exception is thrown at all to identify the issue. So, in UI the status is not updated, and unexpected result is produced. I am not able to identify the issue. Help of any kind will be highly appreciated.
EDIT:
Also, I have to do an operation in parallel. The code for EndReceive is as follows:
private void EndReceive(IAsyncResult ar)
{
try
{
int nBytes;
nBytes = m_NetworkStream.EndRead(ar);
if (nBytes > 0)
{
string res = Encoding.UTF8.GetString(m_ReadBuffer, 0, nBytes);
DeviceStatus status = new DeviceStatus();
string[] readlines = res.Split(new string[] { CRLF }, StringSplitOptions.RemoveEmptyEntries);
foreach (string readline in readlines)
{
if (readline.StartsWith("CODE"))
{
status.code = Convert.ToInt32(readline.Replace("CODE=", ""));
break;
}
}
status.deviceip = this._deviceip;
status.port = this.port;
status.DeviceID = this._DeviceID;
status.FirmwareID = this._FirmwareID;
status.FilePath = this._Path;
StatusUpdate(status);
m_ReadBuffer = new byte[1024];
}
}
catch (ObjectDisposedException ods)
{
return;
}
if (_tcpclient.Connected)
m_NetworkStream.BeginRead(m_ReadBuffer, 0, m_ReadBuffer.Length, new AsyncCallback(EndReceive), null);
}
I'm not sure you should have a while loop in order to write bytes read from a file (from disk) to a network stream ... you can just read all the bytes and write to the stream and flush in one move.
You can also add a write timeout to specify how much time can pass before the stream write operation fails, to prevent any possibility of 'hanging'.
With these modifications, the code would look something like this:
// make the tcp connection to the remote endpoint
_tcpclient = new TcpClient();
_tcpclient.Connect(_deviceip, port);
// read the file bytes in one operation
var allBytes = File.ReadAllBytes(fileNameOnDisk);
// get the network stream
m_NetworkStream = _tcpclient.GetStream();
// wait a max of 500ms for the write operation to happen
m_NetworkStream.WriteTimeout = 500;
// write the file bytes to the stream and flush without while/stream/seek etc.
m_NetworkStream.Write(allBytes, 0, allBytes.Length);
m_NetworkStream.Flush();
And when you've finished with the stream:
m_NetworkStream.Close();
m_NetworkStream.Dispose();
It seem odd that you starting to read from network stream (m_NetworkStream.BeginRead(...)) and right away in another thread starting to write into same stream (m_NetworkStream.Write(...)). I would suggest to finish reading first and then start writing. Also you could use Stream.CopyTo to copy data between streams.
public async Task<bool> UploadFirmware(Stream fileStream, IPEndPoint deviceEP)
{
bool success = false;
try
{
TcpClient client = new TcpClient();
client.Connect(deviceEP);
NetworkStream networkStream = client.GetStream();
BeginReadFromDevice(networkStream);
// send bin data to device
await fileStream.CopyToAsync(networkStream);
success = true;
}
catch (Exception)
{
}
return success;
}
private void BeginReadFromDevice(Stream networkStream)
{
byte[] buffer = new byte[1024];
networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(EndReceive), null);
}

C# FTP Upload Server returned an error: 550 The process cannot access the file because it is being used by another process

Hi I'm trying to upload a file with a passed in byte[] and am getting a 550.
I'm using a Memory stream in a using statement so I thought it should close itself off nicely.
If I'm dealing with a byte array rather than a physical file what could be causing the lock as the byte array doesn't map to a file per-say it is generated by a csv helper.
Basically I build up a csv with a stringbuilder and the call Export which takes the string builder and puts it in to a byte[] which then gets passed in to this method..
Just wondering if anyone could see what I'm doing wrong.
Thanks!
bool PutFileToServer(string remoteFile, byte[] bytesToUpload, bool result)
{
try
{
LogStatus("Creating FTP Request");
var ftpRequest = CreateRequest(remoteFile, WebRequestMethods.Ftp.UploadFile);
using (var dataStream = new MemoryStream(bytesToUpload))
using (var requestStream = ftpRequest.GetRequestStream())
{
dataStream.Position = 0;
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = dataStream.Read(byteBuffer, 0, bufferSize);
LogStatus("Reading File Stream");
try
{
while (bytesSent != 0)
{
requestStream.Write(byteBuffer, 0, bytesSent);
bytesSent = dataStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
LogStatus("Error Reading File Bytes");
LogStatus(ex.Message);
result = false;
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
if (dataStream != null)
{
dataStream.Close();
}
if (requestStream != null)
{
requestStream.Close();
}
if (ftpStream != null)
{
ftpStream.Close();
}
ftpRequest = null;
}
result = true;
}
}
catch (Exception ex)
{
LogStatus(ex.Message);
result = false;
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
if (ftpStream != null)
{
ftpStream.Close();
}
ftpRequest = null;
}
return result;
}

C# TcpClient losing packets

I'm having some issues when I really stress test my networking code. Essentially once the socket is set up it calls this:
NetworkStream networkStream = mClient.GetStream();
networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
private void ReadCallback(IAsyncResult result)
{
try
{
int read;
NetworkStream networkStream;
try
{
networkStream = mClient.GetStream();
read = networkStream.EndRead(result);
}
catch
{
return;
}
if (read == 0)
{
//The connection has been closed.
return;
}
var readBuffer = (byte[])result.AsyncState;
var readCount = readBuffer.Length;
while (readCount < 4)
{
readCount += networkStream.Read(readBuffer, 0, readBuffer.Length - readCount);
}
var length = BitConverter.ToInt32(readBuffer, 0);
var messageBuffer = new byte[length];
readCount = 0;
while (readCount < length)
{
readCount += networkStream.Read(messageBuffer, 0, messageBuffer.Length - readCount);
}
else
{
RaiseMessageReceived(this, messageBuffer);
}
//Then start reading from the network again.
readBuffer = new byte[4]; //may not need to reset, not sure
networkStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, readBuffer);
}
catch(Exception)
{
//Connection is dead, stop trying to read and wait for a heal to retrigger the read queue
return;
}
}
Then the below is my send methods
private byte[] GetMessageWithLength(byte[] bytes)
{
//Combine the msg length to the msg
byte[] length = BitConverter.GetBytes(bytes.Length);
var msg = new byte[length.Length + bytes.Length];
Buffer.BlockCopy(length, 0, msg, 0, length.Length);
Buffer.BlockCopy(bytes, 0, msg, length.Length, bytes.Length);
return msg;
}
public override bool Send(byte[] bytes)
{
lock (sendQueue)
{
sendQueue.Enqueue(bytes);
Interlocked.Increment(ref sendQueueSize);
}
if (!mClient.Connected)
{
if (Connect())
{
RaiseConnectionChanged(this, true, Localisation.TCPConnectionEstablished);
}
else
{
RaiseConnectionChanged(this, false, (bytes.Length > 0 ? Localisation.TCPMessageFailed : Localisation.TCPMessageConnectionLost));
}
}
try
{
NetworkStream networkStream = mClient.GetStream();
lock (sendQueue)
{
if (sendQueue.Count == 0)
{
return true;
}
bytes = sendQueue.Dequeue();
}
var msg = GetMessageWithLength(bytes);
//Start async write operation
networkStream.BeginWrite(msg, 0, msg.Length, WriteCallback, null);
}
catch (Exception ex)
{
RaiseConnectionChanged(this, false, (bytes.Length > 0 ? Localisation.TCPMessageFailed : Localisation.TCPMessageConnectionLost));
}
return true;
}
/// <summary>
/// Callback for Write operation
/// </summary>
/// <param name="result">The AsyncResult object</param>
private void WriteCallback(IAsyncResult result)
{
try
{
NetworkStream networkStream = mClient.GetStream();
while (sendQueue.Count > 0)
{
byte[] bytes;
lock (sendQueue)
{
if (sendQueue.Count == 0)
{
break;
}
bytes = sendQueue.Dequeue();
}
var msg = GetMessageWithLength(bytes);
networkStream.Write(msg, 0, msg.Length);
Interlocked.Decrement(ref sendQueueSize);
}
networkStream.EndWrite(result);
mLastPacketSentAt = Environment.TickCount;
Interlocked.Decrement(ref sendQueueSize);
}
catch (Exception ex)
{
RaiseConnectionChanged(this, false, Localisation.TCPMessageConnectionLost);
}
}
But yea, at some point when I stress test the system (say 500 or so clients sending lots of messages at once), I notice maybe 1 packet in every 4 million to just not get recieved. I'm not sure if the issue lies in the sending or the recieving, which is why I have included both methods. However I will point out that if I choose to send another packet from the client, it still sends and receives correctly, so it is not just queued or something.
Can anyone see something I am missing?
The two read loops (e.g. while (readCount < length)) are buggy. You always read at offset zero. You should read at an ever-increasing offset.
This lead to overwriting of already-read data.
Also, I'm not sure if it is a good idea to mix synchronous and asynchronous reads. You lose the benefit of asynchronous code that way and still have to deal with callbacks and such. I think you should decide on one style and stick to it.

Sending large objects over TCP: "End of Stream encountered before parsing was completed"

I keep getting an SerializationException whenever I try to deserialize a list of doubles from a NetworkStream:
End of Stream encountered before
parsing was completed
I have a simple client server architecture: my TcpTransportClient wraps the functionality of a TcpClient and I utilize two basic methods: Send (sends a message) and Receive (blocks until a message is received).
The Send function takes a Message, serializes it using a BinaryFormatter and sends the bytes via the NetworkStream.
public void Send(Message message)
{
if (message == null)
{
throw new TransportException("Invalidate Parameter In Send Call");
}
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}
lock (_sync)
{
// Serialzie the message
MemoryStream memStream = new MemoryStream();
_serializer.Serialize(memStream, message);
// Get the bytes of of the memory stream
byte[] buffer = memStream.GetBuffer();
// Write the message to the network stream
NetworkStream networkStream = _tcpClient.GetStream();
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
}
}
The receive function reads bytes into a buffer from the NetworkStream, then deserializes the message by using a BinaryFormatter:
public Message Receive()
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}
byte[] buffer;
MemoryStream memStream = new MemoryStream();
NetworkStream netStream = _tcpClient.GetStream();
try
{
do
{
// Allocate a new buffer
buffer = new byte[_tcpClient.ReceiveBufferSize];
// Read the message buffer
int sizeRead = netStream.Read(buffer, 0, buffer.Length);
// Write the buffer to the memory stream
memStream.Write(buffer, 0, sizeRead);
} while (netStream.DataAvailable);
// Reset the memory stream position
memStream.Position = 0;
// Deserialize the message
object tmp = _deserializer.Deserialize(memStream); // <-- The exception is here!
// Cast the object to a message
return (Message)tmp;
}
catch (System.Exception e)
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}
else
{
throw e;
}
}
}
I have a basic sending thread:
TcpTransportClient client = new TcpTransportClient(GetLocalAddress(), servicePort);
client.Connect();
Thread sendThread = new Thread(() =>
{
List<double> dataSet = new List<double>();
for (double d = 0.0; d < 500.0; d++)
{
dataSet.Add(d);
}
while (true)
{
try
{
// Serialize the data set
MemoryStream memStream = new MemoryStream();
BinaryFormatter binFormat = new BinaryFormatter();
binFormat.Serialize(memStream, (object)dataSet);
// Create a message
Message msg = new Message();
// Hold the object bytes in an opaque field
msg.SetFieldValue(1000, memStream.GetBuffer());
// Set the message topic
msg.SetTopic("client.dataSet");
// Send the message
client.Send(msg);
// Sleep
Thread.Sleep(3000);
}
catch (TransportException)
{
break;
}
catch(Exception)
{
//ignore it
}
}
});
sendThread.IsBackground = true;
sendThread.Start();
And a receive thread which gets started whenever a TcpClient is accepted:
public void HandleAcceptedClient(TcpTransportClient client)
{
Thread receiveThread = new Thread(() =>
{
while (true)
{
try
{
Message msg = client.Receive();
Trace.WriteLine("Server Received: " + msg.GetTopic());
byte[] buffer = msg.GetFieldOpaqueValue(1000);
MemoryStream memStream = new MemoryStream(buffer);
BinaryFormatter binFormat = new BinaryFormatter();
List<double> dataSet = (List<double>)binFormat.Deserialize(memStream);
if (dataSet.Count == 500)
{
Trace.WriteLine(DateTime.Now + ": OK");
}
else
{
Trace.WriteLine(DateTime.Now + ": FAIL");
}
}
catch (TransportException)
{
break;
}
catch(Exception)
{
// ignore it
}
}
});
receiveThread.IsBackground = true;
receiveThread.Start();
}
The exception always occurs when I try to deserialize the message in Receive method of my TcpTransportClient, but the problem only occurs if I put some data in the data set. What's the proper way to send a list of values over a network and successfully deserialize them on the receiving end?
P.S. I tried the solution in a nearly identical question, but it didn't work: I'm still getting the same exception.
while (netStream.DataAvailable);
That's not correct. You should stop reading when the Read() call returns 0. The DataAvailable property just tells you whether or not the Read() call will block, waiting to allow the server to catch up.
You need message framing.

Categories

Resources