It is working really good except sometimes (noticed on vista only so far)
I am trying to create a robust Async Socket.BeginReceive process. Currently all I do is connect to the server, server acknowledges connection and sends a file to the client. Client parses a prefix, and processes the file via BinaryWriter.
TCP ****BufferSize = 1024****
EDIT: Have re-worked functionality to make it more robust Workflow is as follows;
Send: - I send 8 byte prefix packet which is two integers. (First Int is the file size expected, second int is the prefix size expected, then the file itself is next.
Receive:
After I have undoubtedly received the first 8 bytes, I process the prefix converting the first 4 bytes into an integer (file size byte length) then convert the next 4 bytes into an integer (prefix size byte length)
I then undoubtedly receive the prefix size byte length off the buffer, and process my prefix.
I then begin to receive my file based on file size byte length store in the prefix message.
Problem: Everything works good locally. I have tested checksums and file data after sending and receiving and everything looks good.
However commercial environment (noticed on vista), once in a while (not always, most of the time transmission is successful) I will get a System.IO.IOException: The process cannot access the file 'C:\TestReceived.txt' ... Here is a screen shot of the exact error.
What I think's going on, is since the beginRecieve
is being called async on a separate thread, sometimes both threads try to access the filestream at the same time via BinaryWriter
.
I tried initalizing the Binary writer with FileShare.None as I read that it will lock the file.
BinaryWriter writer = new BinaryWriter(File.Open(state.receivedPath, FileMode.Append,FileAccess.Write,FileShare.None));
It doesn't seem to be locking the file as expected because this does not resolve the issue.
Question: Can any of the guru's direct me how to properly lock the FileStream? I have indicated in the ReceiveCallback
where I believe I am going wrong.
EDIT: Solution: So I ended up discovering that perhaps I wasnt cleaning up my resources used to create / append to the file. I've switched to the using statement to initialize my FileStream
object and BinaryWriter
object in hopes that it would manage the clean up better, and it seems to be working :) Have not had a failed test all day. Now time to handle exceptions on the server side! Thank you all for your help.
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
state.totalBytesRead += bytesRead;
if (bytesRead > 0)
{
if (state.flag == 0)
{
if (state.totalBytesRead >= 8)
{
// we know we put the msgLen / prefixLen as the first 8 bytes on the stream
state.msgLen = BitConverter.ToInt32(state.buffer, 0);
state.prefixLen = BitConverter.ToInt32(state.buffer, 4);
state.flag = 1;
// good to process the first 2 integer values on the stream
//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 8, bytesRead));
int prefixRequestBytes = state.prefixLen;
if (prefixRequestBytes > StateObject.BufferSize)
prefixRequestBytes = StateObject.BufferSize;
state.lastSendByteCount = prefixRequestBytes;
state.totalBytesRead = 0;
// start re-writing to the begining of the buffer since we saved
client.BeginReceive(state.buffer, 0, prefixRequestBytes, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
else
{
int bytesToSend = state.lastSendByteCount - bytesRead;
state.lastSendByteCount = bytesToSend;
// need to receive atleast first 8 bytes to continue
// Get the rest of the data.
client.BeginReceive(state.buffer, state.totalBytesRead, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
if (state.flag == 1)
{
// we are expexing to process the prefix
if (state.totalBytesRead >= state.prefixLen)
{
// we are good to process
// Lets always assume that our prefixMsg can fit into our prefixbuffer ( we wont send greater than prefixbuffer)
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,state.prefixLen));
string prefixMsg = state.sb.ToString();
state.receivedPath = @"C:\TestReceived.txt";
state.flag++;
int msgRequestBytes = state.msgLen;
if (msgRequestBytes > StateObject.BufferSize)
msgRequestBytes = StateObject.BufferSize;
state.lastSendByteCount = msgRequestBytes;
state.totalBytesRead = 0;
// should be good to process the msg now
// start re-writing to the begining of the buffer since we saved
client.BeginReceive(state.buffer, 0, msgRequestBytes, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
else
{
int bytesToSend = state.lastSendByteCount - bytesRead;
state.lastSendByteCount = bytesToSend;
// request the rest of the prefix
// Get the rest of the data.
client.BeginReceive(state.buffer, state.totalBytesRead, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
// we are expecting to process the file
if (state.flag > 1)
{
// I think here, the binarywriter needs to be locked
if (state.totalBytesRead >= state.msgLen)
{
Console.WriteLine("Writing final {0} bytes to server", bytesRead);
BinaryWriter writer = new BinaryWriter(File.Open(state.receivedPath, FileMode.Append,FileAccess.Write,FileShare.None));
writer.Write(state.buffer, 0, bytesRead);
writer.Close();
Console.WriteLine("Finished reading file");
}
else
{
Console.WriteLine("Reading {0} bytes from server...", bytesRead);
// Padd these bytes
BinaryWriter writer = new BinaryWriter(File.Open(state.receivedPath, FileMode.Append, FileAccess.Write, FileShare.None));
writer.Write(state.buffer, 0, bytesRead);
writer.Close();
// get how many more bytes are left to read
int bytesToSend = state.msgLen - bytesRead;
if (bytesToSend > StateObject.BufferSize)
bytesToSend = StateObject.BufferSize;
client.BeginReceive(state.buffer, 0, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
}
else
{
// All the data has arrived;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
My send is quite straight forward because I use the Socket.BeginSendFile(..); All I do here is tack on my prefix, and send the file.
private static void Send(Socket handler)
{
string msg = "Fetching...<EOF>";
byte[] prefixMsg = Encoding.ASCII.GetBytes(msg);
FileInfo fi = new FileInfo(@"C:\test.txt");
byte[] fileLen = BitConverter.GetBytes(fi.Length); // The length of the file msg, we will use this to determin stream len
byte[] prefixMsgLen = BitConverter.GetBytes(prefixMsg.Length); // the length of the prefix msg, we will use this to determin head len
// copy out prefix to a prefix byte array
byte[] prefix = new byte[ 4 + 4 + prefixMsg.Length];
fileLen.CopyTo(prefix, 0);
prefixMsgLen.CopyTo(prefix, 4);
prefixMsg.CopyTo(prefix, 8);
// *** Receive design requires prefixmsg.length to fit into prefix buffer
handler.BeginSendFile(fi.FullName, prefix, null, 0, new AsyncCallback(AsynchronousFileSendCallback), handler);
}
Thank you very much for your time.