Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9231249
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T06:01:22+00:00 2026-06-18T06:01:22+00:00

It is working really good except sometimes (noticed on vista only so far) I

  • 0

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.

enter image description here

    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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T06:01:23+00:00Added an answer on June 18, 2026 at 6:01 am

    You are aware that the amount of bytes received in a single read operation might be as low as 1 byte, regardless of the amount requested?

    This being the case, you need to read again (asynchronously) until you have received the number of bytes that you expect.

    I would also suggest that you gather better data at the point of failure. Consider using http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx with a logging library to capture more info. In the mean time, have you taken a look at the windows application log on the affected machine? There should be a basic stacktrace of sorts in there.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working on a presentation about RoR. It's looking good except I cannot
I've recently begun working in Sproutcore, which seems to be a really good solution
I've started using PHP lately... all is good except one thing. I am trying
I was using CouchBase Server 1.1.1 for Mac and it's working really well. It
I'm converting a large, multi-project CVS repository into Subversion using cvs2svn. It's working really
I really love working with Django and Python, when I go back to PHP
I have started using MVC 3 and I really like working with it. It's
I really want to know your experience at working with ADO.Net datasets (calling stored
I really wish Processing had push and pop methods for working with Arrays, but
I really can't understand how the below piece of code is working... options.each {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.