473,404 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Large file transfer in chunks from client to server using Socket asynch using c#

I'm developing a c# asynchronous socket application for tranfering file or large data from client to server and server to client as well in chunks.

Application sometimes transfer file from client to server and sometimes not,
because connection betwenn client and server closed Abrupt.

I cannot understand why connection between client and server is closed while i cannot closed the connection until a single block
tranfered to server.

my client i.e. FileTransfer Application work in this manner
-----------------------------------------------------------
  1. define a bufferSize of type int to read block of data from file
  2. sendFile() function receive a file name like "E:/UplodingFile/abc.doc" or some other file i want to transfer
  3. read file using BinaryReader class of .Net
  4. create a byte array "bSentData" of size either file content length or buffer size whichever is less
  5. now sundFile() function goes into while loop and continue till the length of the file read.
  6. in the while loop, read block of data into bSentData byte array
  7. convert bSentData to Base64String, this is because this is my test application, and when this code runiing smoothly i incoroporate this to my office development library .
  8. append other necessary information to a StringBuilder variable
  9. now instatiate a socket object and call socket.BeginConnect for connection to server application with delegate aynccallback function
  10. using the ManualResetEvent ConnectDone, set ConnectDone.WaitOne();
  11. in asynccallback delegate function "onConnectedToSerever", call EndConnect. and set ConnectDone.Set() that a connection has been made
  12. now get total length of data to be sent to server
  13. send size information to server and using BeginSend
  14. wait for receiving response from server that server receive the data size.
  15. send actual data to server using BeginSend
  16. wait for response from server that server receive data.
  17. after calling seting ConnectDone.WaitOne() at step 10, increase block counter and check either socket connected to server or not if socket connected to server close connection to server
  18. repeat step 6 to 17 until complete file is tranfered to server.

Server FileReceiver Application work in this manner
----------------------------------------------------
  1. Server start listening on specific port.
  2. waiting for connection from client calling BeginAccept
  3. when a request arrive for establishing a connection, establishing a connection to client by calling EndAccept
  4. call function WaitForData, create stateobject class object, function waiting for receiving data from client using BeginReceive
  5. BeginReceive callback function OnReceive, receive request by calling EndReceive,
  6. OnReceive function add bytes receive to stateobject class variable BytesReceived
  7. onreceive function verify that thata stateobject.messgaesize variable of stateobject call is -1, meaning that client now sending data size to server.
  8. if bytesreceived == 4, we have receive the size of the data and read its value.
  9. send response to clinet waiting from server that server has received the data size.
  10. create stateobject byte array variable buffer to data size received.
  11. call beginReceive again from OnReceive function to read actual data from client untill we read all data i.e. stateobject.bytesreceived = stateobject.messagesize
  12. when we received complete data from client,send a response to client that we have received complete data and process our data

Client Code
-----------
Expand|Select|Wrap|Line Numbers
  1.  
  2. class FileHandling
  3.     {
  4.         // ManualResetEvent instances signal completion.
  5.         private static ManualResetEvent connectDone =
  6.             new ManualResetEvent(false);
  7.         private static ManualResetEvent sendSizeDone =
  8.             new ManualResetEvent(false);
  9.         private static ManualResetEvent sendDataDone =
  10.             new ManualResetEvent(false);
  11.         private static ManualResetEvent receiveSizeDone =
  12.             new ManualResetEvent(false);
  13.         private static ManualResetEvent receiveDataDone =
  14.             new ManualResetEvent(false);
  15.  
  16.         // Get the remote IP address
  17.         private static IPAddress ip = IPAddress.Parse("127.0.0.1"); //"10.0.0.9"
  18.  
  19.         // Create the end point 
  20.         private static IPEndPoint ipEnd = new IPEndPoint(ip, 1200);        
  21.         public void SendLargeFile(string sFileName)
  22.         {
  23.             string sRequest = string.Empty;
  24.             try
  25.             {
  26.                 if (sFileName.Length < 1)
  27.                 {
  28.                     MessageBox.Show("No file selected");
  29.                     return;
  30.                 }
  31.                 SendFile(sFileName);
  32.                 MessageBox.Show("File Transfered");
  33.             }
  34.             catch (Exception objEx)
  35.             {
  36.                 MessageBox.Show(objEx.Message);
  37.             }
  38.         }
  39.  
  40.         #region SendFile
  41.         private void SendFile(string sSentFileName)
  42.         {  
  43.             Socket m_clientSocket = null;           
  44.             string sAppendRequest = "",
  45.                 sCurrentFileName = string.Empty,
  46.                 sBufferData = string.Empty;
  47.             int iTotalSentDataSize = 0;
  48.             int iTotalSentDataSlot = 0;
  49.             byte[] bSentData = null;
  50.             BinaryReader ObjBinReader = null;
  51.  
  52.             byte[] sizeinfo = new byte[4];
  53.             byte[] dataBuffer = null;            
  54.             try
  55.             {
  56.                 int iBufferSize = 20480;
  57.                 sCurrentFileName = sSentFileName.Replace(@"\", "/");                                
  58.                 ObjBinReader = new BinaryReader(File.Open(sCurrentFileName, FileMode.Open));
  59.                 while (sCurrentFileName.IndexOf("/") != -1)
  60.                 {
  61.                     sCurrentFileName = sCurrentFileName.Substring(sCurrentFileName.IndexOf("/") + 1);
  62.                 }                
  63.                 if (ObjBinReader.BaseStream.Length < iBufferSize)
  64.                 {
  65.                     bSentData = new byte[ObjBinReader.BaseStream.Length];
  66.                     iBufferSize = (int)ObjBinReader.BaseStream.Length;
  67.                 }
  68.                 else
  69.                 {
  70.                     bSentData = new byte[iBufferSize];
  71.                 }
  72.  
  73.                 while ((iBufferSize * iTotalSentDataSlot) < ObjBinReader.BaseStream.Length)
  74.                 {
  75.                     sAppendRequest = "";
  76.                     if (iBufferSize * (iTotalSentDataSlot + 1) < ObjBinReader.BaseStream.Length)
  77.                     {
  78.                         ObjBinReader.Read(bSentData, 0, iBufferSize);
  79.                         sBufferData =  Convert.ToBase64String(bSentData);
  80.                         iTotalSentDataSize += iBufferSize;
  81.                         sAppendRequest = (iTotalSentDataSlot + 1).ToString().PadRight(20, ' '); // 0-19
  82.                         sAppendRequest += (sBufferData.Length).ToString().PadRight(20, ' ');      // 20-39
  83.                         sAppendRequest += (iTotalSentDataSize).ToString().PadRight(20, ' ');  // 40 - 59
  84.                         sAppendRequest += (sCurrentFileName + "." + iTotalSentDataSlot).ToString().PadRight(100, ' '); // 60 - 159
  85.                         sAppendRequest += sBufferData.ToString().PadRight(27400, ' ');  // 160 - 27559
  86.                     }
  87.                     else
  88.                     {
  89.                         int iRemLen = (int)ObjBinReader.BaseStream.Length - iBufferSize * iTotalSentDataSlot;
  90.                         bSentData = new byte[iRemLen];
  91.                         ObjBinReader.Read(bSentData, 0, iRemLen);
  92.                         sBufferData = Convert.ToBase64String(bSentData); 
  93.                         iTotalSentDataSize += iRemLen;
  94.                         sAppendRequest = (iTotalSentDataSlot + 1).ToString().PadRight(20, ' ');
  95.                         sAppendRequest += (sBufferData.Length).ToString().PadRight(20, ' '); 
  96.                         sAppendRequest += iTotalSentDataSize.ToString().PadRight(20, ' ');
  97.                         sAppendRequest += (sCurrentFileName + "." + iTotalSentDataSlot + ".E").ToString().PadRight(100, ' ');
  98.                         sAppendRequest += sBufferData.ToString().PadRight(27400, ' ');
  99.                     }
  100.                     m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  101.                     m_clientSocket.NoDelay = true;   
  102.                     StateObject stateObject = new StateObject(m_clientSocket, sAppendRequest);
  103.                     // Connect to the remote host
  104.                     m_clientSocket.BeginConnect(ipEnd, new AsyncCallback(onConnectedToSerever), stateObject);                    
  105.                     // wait for the connection to be made
  106.                     connectDone.WaitOn();                 
  107.                     iTotalSentDataSlot++;
  108.                     if (m_clientSocket.Connected)
  109.                     {
  110.                         m_clientSocket.Shutdown(SocketShutdown.Both);
  111.                         m_clientSocket.Close();
  112.                     }
  113.                 }                
  114.             }
  115.             catch (Exception objEx)
  116.             {
  117.                 MessageBox.Show("SendFile : " +objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  118.             }
  119.             finally
  120.             {
  121.                 if (ObjBinReader != null)
  122.                     ObjBinReader.Close();               
  123.             }
  124.         }
  125.  
  126.         #endregion
  127.  
  128.         private void onConnectedToSerever(IAsyncResult iar)
  129.         {
  130.             try
  131.             {
  132.                 StateObject stateObject = (StateObject)iar.AsyncState;
  133.                 stateObject.workerSocket.EndConnect(iar);
  134.                 // Signal that the connection has been made
  135.                 connectDone.Set();
  136.                 stateObject.dataBuffer = Encoding.ASCII.GetBytes(stateObject.sMessage);
  137.                 byte[] sizeinfo = new byte[4];
  138.                 sizeinfo[0] = (byte)stateObject.dataBuffer.Length;
  139.                 sizeinfo[1] = (byte)(stateObject.dataBuffer.Length >> 8);
  140.                 sizeinfo[2] = (byte)(stateObject.dataBuffer.Length >> 16);
  141.                 sizeinfo[3] = (byte)(stateObject.dataBuffer.Length >> 24);
  142.  
  143.                 SendDataSize(stateObject, sizeinfo);
  144.                 sendSizeDone.WaitOne();
  145.  
  146.                 ReceiveDataSize(stateObject);
  147.                 receiveSizeDone.WaitOne();
  148.  
  149.                 SendData(stateObject, stateObject.dataBuffer);
  150.                 sendDataDone.WaitOne();
  151.  
  152.                 ReceiveData(stateObject);
  153.                 receiveDataDone.WaitOne();               
  154.             }
  155.             catch (Exception objEx)
  156.             {
  157.                 MessageBox.Show("OnConnectedToServer : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  158.             }
  159.         }
  160.  
  161.         private void SendData(StateObject stateObject, byte[] data)
  162.         {
  163.             try
  164.             {                
  165.                 stateObject.workerSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnSendToSever), stateObject);
  166.             }
  167.             catch (Exception objEx)
  168.             {
  169.                 MessageBox.Show("SendData : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  170.             }
  171.         }
  172.  
  173.         private void SendDataSize(StateObject stateObject, byte[] data)
  174.         {
  175.             try
  176.             {
  177.                 stateObject.workerSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnSizeSendToSever), stateObject);
  178.             }
  179.             catch (Exception objEx)
  180.             {
  181.                 MessageBox.Show("SendDataSize : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  182.             }
  183.         }
  184.  
  185.         private void ReceiveDataSize(StateObject stateObject)
  186.         {
  187.             try
  188.             {
  189.                 StateObject receiveState = new StateObject(stateObject.workerSocket);
  190.                 receiveState.workerSocket.BeginReceive(receiveState.dataBuffer, 0, receiveState.dataBuffer.Length, SocketFlags.None, new AsyncCallback(OnSizeReceiveFromServer), receiveState);
  191.             }
  192.             catch (Exception objEx)
  193.             {
  194.                 MessageBox.Show("ReceiveDataSize : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  195.             }
  196.             finally
  197.             {                 
  198.             }
  199.         }
  200.  
  201.         private void ReceiveData(StateObject stateObject )
  202.         {
  203.             try
  204.             {
  205.                 StateObject receiveState = new StateObject(stateObject.workerSocket);
  206.                 receiveState.workerSocket.BeginReceive(receiveState.dataBuffer, 0, receiveState.dataBuffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceiveFromServer), receiveState);
  207.             }
  208.             catch (Exception objEx)
  209.             {
  210.                 MessageBox.Show("ReceiveData : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  211.             }
  212.             finally
  213.             {
  214.             }
  215.         }
  216.  
  217.         private void OnSizeSendToSever(IAsyncResult m_asyncResult)
  218.         {
  219.             try
  220.             {
  221.                 StateObject stateObject = (StateObject)m_asyncResult.AsyncState;
  222.                 int iBytesSend = stateObject.workerSocket.EndSend(m_asyncResult);
  223.  
  224.                 // Signal that all bytes have been sent.
  225.                 sendSizeDone.Set();
  226.             }
  227.             catch (Exception objEx)
  228.             {
  229.                 MessageBox.Show("OnSizeSendToSever : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  230.             }
  231.         }
  232.  
  233.         private void OnSendToSever(IAsyncResult m_asyncResult)
  234.         {
  235.             try
  236.             {
  237.                 StateObject stateObject = (StateObject)m_asyncResult.AsyncState;
  238.                 int iBytesSend = stateObject.workerSocket.EndSend(m_asyncResult);
  239.  
  240.                 // Signal that all bytes have been sent.
  241.                 sendDataDone.Set();
  242.             }
  243.             catch (Exception objEx)
  244.             {
  245.                 MessageBox.Show("OnSendToServer : " + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  246.             }
  247.         }
  248.  
  249.         private void OnSizeReceiveFromServer(IAsyncResult iar)
  250.         {
  251.             try
  252.             {
  253.                 StateObject state = (StateObject) iar.AsyncState;
  254.                 Socket client = state.workerSocket;
  255.  
  256.                 int bytesRead = client.EndReceive(iar);
  257.  
  258.                 // There might be more data, so store the data received so far.
  259.                 state.sMessage += Encoding.ASCII.GetString(state.dataBuffer, 0, bytesRead);
  260.  
  261.                 // Signal that all bytes have been received.
  262.                 receiveSizeDone.Set();                       
  263.             }
  264.             catch(SocketException objEx)            
  265.             {
  266.                 MessageBox.Show("OnSizeReceiveFromServer :" + objEx.Message + "; Stack Trace :" + objEx.StackTrace + " ErrorCode : " + objEx.ErrorCode + " Source : " + objEx.Source);
  267.             }
  268.             catch (Exception objEx)
  269.             {
  270.                 MessageBox.Show("OnSizeReceiveFromServer :" + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  271.             }
  272.         }
  273.  
  274.         private void OnDataReceiveFromServer(IAsyncResult iar)
  275.         {
  276.             try
  277.             {
  278.                 StateObject state = (StateObject)iar.AsyncState;
  279.                 Socket client = state.workerSocket;
  280.  
  281.                 int bytesRead = client.EndReceive(iar);
  282.  
  283.                 // There might be more data, so store the data received so far.
  284.                 state.sMessage += Encoding.ASCII.GetString(state.dataBuffer, 0, bytesRead);
  285.  
  286.                 // Signal that all bytes have been received.
  287.                 receiveDataDone.Set();
  288.             }
  289.             catch (SocketException objEx)
  290.             {
  291.                 MessageBox.Show("OnDataReceiveFromServer :" + objEx.Message + "; Stack Trace :" + objEx.StackTrace + " ErrorCode : " + objEx.ErrorCode + " Source : " + objEx.Source);
  292.             }
  293.             catch (Exception objEx)
  294.             {
  295.                 MessageBox.Show("OnDataReceiveFromServer :" + objEx.Message + "; Stack Trace :" + objEx.StackTrace);
  296.             }
  297.         }
  298.     }
  299. #region Class StateObject to receive data from connected remote server
  300.     public class StateObject
  301.     {
  302.         public StateObject(Socket workerSocket)
  303.         {
  304.             this.workerSocket = workerSocket;
  305.             this.sMessage = "";
  306.         }
  307.  
  308.         public StateObject(Socket workerSocket, string sMessage)
  309.         {
  310.             this.workerSocket = workerSocket;
  311.             this.sMessage = sMessage;
  312.         }
  313.         // Received Data buffer Size
  314.         public const int iBufferSize = 50000;
  315.         // Received Data Buffer
  316.         public byte[] dataBuffer = new byte[iBufferSize];       
  317.         //sending message to server
  318.         public string sMessage = string.Empty;
  319.         // Client Socket         
  320.         public System.Net.Sockets.Socket workerSocket;        
  321.     }
  322.     #endregion 
  323.  
  324.  
,

Server Code
------------
Expand|Select|Wrap|Line Numbers
  1.  
  2. public partial class Form1 : Form
  3.     {       
  4.         // Thread signal.
  5.         public static ManualResetEvent allDone = new ManualResetEvent(false);
  6.         public delegate void UpdateMessageBoxDelegate(string sText);
  7.         public Form1()
  8.         {
  9.             InitializeComponent();
  10.         }
  11.  
  12.         private void Start_Click(object sender, EventArgs e)
  13.         {
  14.             try
  15.             {
  16.                 //create the listening socket...
  17.                 Socket m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  18.                 IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 1200);               
  19.  
  20.                 //bind to local IP Address...
  21.                 m_socListener.Bind(ipLocal);
  22.                 //start listening...               
  23.                 m_socListener.Listen(500);
  24.                 richTextBox1.Text = "Start Listening \n";
  25.                 label1.Text = "Server is in listening mode";
  26.                 Start.Enabled = false;
  27.                 while (true)
  28.                 {
  29.                     // Set the event to nonsignaled state.
  30.                     allDone.Reset();
  31.                     m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), m_socListener);
  32.  
  33.                     // Wait until a connection is made before continuing.
  34.                     allDone.WaitOne();
  35.                 }
  36.             }
  37.             catch (Exception ObjEx)
  38.             {
  39.                 // Create Error Log            
  40.                 MessageBox.Show("Start_Click :" + ObjEx.Message);
  41.             }
  42.         }
  43.  
  44.         public void OnClientConnect(IAsyncResult asyn)
  45.         {
  46.             // Signal the main thread to continue.
  47.             allDone.Set();
  48.             try
  49.             {
  50.                 Socket listner = (Socket)asyn.AsyncState ;
  51.                 Socket workerSocket = listner.EndAccept(asyn);              
  52.                 WaitForData(workerSocket);                
  53.             }
  54.             catch (ObjectDisposedException ObjEx)
  55.             {
  56.                 MessageBox.Show("OnClientConnect_ObjectDisposedException :" + ObjEx.Message + "; Stack Trace :" + ObjEx.StackTrace);
  57.             }
  58.             catch (SocketException ObjEx)
  59.             {
  60.                 MessageBox.Show("OnClientConnect_SocketException:" + ObjEx.Message + "; Stack Trace :" + ObjEx.StackTrace);
  61.             }
  62.         }
  63.  
  64.         #region WaitForData
  65.         public void WaitForData(System.Net.Sockets.Socket workerSocket)
  66.         {
  67.             try
  68.             {
  69.                 StateObject stateObject = new StateObject(workerSocket);               
  70.                 // now start to listen for any data...
  71.                 workerSocket.BeginReceive(stateObject.buffer, 
  72.                     0, 
  73.                     stateObject.buffer.Length, 
  74.                     SocketFlags.None, 
  75.                     new AsyncCallback(OnDataReceived), 
  76.                     stateObject);
  77.             }
  78.             catch (SocketException ObjEx)
  79.             {
  80.                 // Create Err Log
  81.                 MessageBox.Show("WaitForData:" + ObjEx.Message + "; Stack Trace :" + ObjEx.StackTrace);
  82.             }
  83.         }
  84.         #endregion
  85.  
  86.         #region OnDataReceived
  87.         public void OnDataReceived(IAsyncResult asyn)
  88.         {   
  89.             try
  90.             {
  91.                 StateObject stateObject = asyn.AsyncState as StateObject;
  92.                 Socket handler = stateObject.workerSocket;
  93.                 int iCount = handler.EndReceive(asyn);
  94.                 stateObject.bytesReceived += iCount;
  95.                 if (stateObject.messageSize == -1) // we still reding the size of the message
  96.                 {
  97.                     if (iCount == 0)
  98.                     {
  99.                         MessageBox.Show("The remote peer closed the connection while reding the message size");
  100.                         throw new ProtocolViolationException("The remote peer closed the connection while reding the message size");
  101.                     }
  102.  
  103.                     if (stateObject.bytesReceived == 4) // we are reding size of the data
  104.                     {
  105.                         //read size of the message
  106.                         stateObject.messageSize = BitConverter.ToInt32(stateObject.buffer, 0);
  107.                         //Send confirmation to client that server has received message size
  108.                         byte[] respond = Encoding.ASCII.GetBytes("Ok : received size of the data");
  109.                         handler.BeginSend(respond,
  110.                             0,
  111.                             respond.Length,
  112.                             SocketFlags.None,
  113.                             new AsyncCallback(OnSendToClient),
  114.                             handler);
  115.  
  116.                         if (stateObject.messageSize < 0)
  117.                         {
  118.                             MessageBox.Show("the remote peer send a negative size messsage");
  119.                             throw new ProtocolViolationException("the remote peer send a negative size messsage");
  120.                         }
  121.  
  122.                         //only message size data be received
  123.                         stateObject.buffer = new byte[stateObject.messageSize];
  124.                         // reset the receiving bytes
  125.                         stateObject.bytesReceived = 0;
  126.                     }
  127.                     if (stateObject.messageSize != 0)
  128.                     {
  129.                         // we need more data either message size information
  130.                         // or
  131.                         // it could be the message body
  132.                         // only time we need no data when message size =0
  133.  stateObject.workerSocket.BeginReceive(stateObject.buffer,
  134.                             stateObject.bytesReceived,
  135.                             stateObject.buffer.Length - stateObject.bytesReceived,
  136.                             SocketFlags.None,
  137.                                 new AsyncCallback(OnDataReceived),
  138.                             stateObject);
  139.                     }
  140.                     else
  141.                     { 
  142.                         //we have received the zero size message
  143.                         MessageBox.Show("we have received the zero size message");
  144.                         //objState.Dispose();
  145.                     }
  146.                 }
  147.                 else // we are reading the body of the message
  148.                 {
  149.                     if (stateObject.bytesReceived == stateObject.messageSize) // we have received the entire message
  150.                     {
  151.                         // send confimation to cleint that server has received the entire message
  152.                         byte[] responde = Encoding.ASCII.GetBytes("Ok : received entire message");
  153.                         handler.BeginSend(responde,
  154.                             0,
  155.                             responde.Length,
  156.                             SocketFlags.None,
  157.                             new AsyncCallback(OnSendToClient),
  158.                             handler);
  159.  
  160.                         // call function that will read bytes from objstate.buffer
  161.                         if (ProcessData(Encoding.ASCII.GetString(stateObject.buffer)))
  162.                         {
  163.                             stateObject.Dispose();
  164.                         }
  165.                     }
  166.                     else // we need more data
  167.                     {
  168.                         if (iCount == 0)
  169.                         {
  170.                             MessageBox.Show("The remote peer closed the connection before the entire message was received");
  171.                             throw new ProtocolViolationException("The remote peer closed the connection before the entire message was received");
  172.                         }
  173. stateObject.workerSocket.BeginReceive(stateObject.buffer,
  174.                             stateObject.bytesReceived,
  175.                             stateObject.buffer.Length - stateObject.bytesReceived,
  176.                             SocketFlags.None,
  177.                             new AsyncCallback(OnDataReceived),
  178.                         stateObject);
  179.                     }                
  180.                 }
  181.             }
  182.             catch (ObjectDisposedException objEx)
  183.             {
  184.                 //System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  185.                 MessageBox.Show("OnDataReceived: Socket has been closed :ObjectDisposedException  " + "; Stack Trace :" + objEx.StackTrace);
  186.             }
  187.             catch (SocketException ObjEx)
  188.             {
  189.                 // Create Err Log        
  190.                 //System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  191.                 MessageBox.Show("OnDataReceived: Socket has been closed :SocketException  " + "; Stack Trace :" + ObjEx.StackTrace);
  192.             }
  193.             catch (Exception objex)
  194.             {
  195.                 MessageBox.Show("OnDataReceived :"+ objex.Message + "; Stack Trace :" + objex.StackTrace + " Source : "+ objex.Source);
  196.             }
  197.             finally
  198.             { 
  199.                string sfinally = "";
  200.             }            
  201.         }
  202.         #endregion
  203.  
  204.         private void OnSendToClient(IAsyncResult iar)
  205.         {
  206.             try
  207.             {
  208.                 Socket socket = iar.AsyncState as Socket;
  209.                 int iBytesSend = socket.EndSend(iar);
  210.             }
  211.             catch (Exception objEx)
  212.             {
  213.                 MessageBox.Show("OnsendToClient : Message : "+objEx.Message + "; Stack Trace : " + objEx.StackTrace + "; Source : " + objEx.Source );
  214.             }
  215.         }
  216.         private bool ProcessData(string szData)
  217.         {
  218.             string sRequest = string.Empty, sBufferData = string.Empty;
  219.             string sEndPart = string.Empty;
  220.             string sOrgFile = string.Empty,
  221.                     sCurrentFileName,
  222.                     sNextFileName = string.Empty;
  223.             bool status = false;
  224.             int iTotalSentDataSize = 0;
  225.             int iTotalSentDataSlot = 0;
  226.             int iBufferSize = 0;
  227.             short iCounter = 0;
  228.             byte[] bBufferData = null;
  229.             BinaryWriter ObjBinaryWriter = null;
  230.             try
  231.             {
  232.                 iTotalSentDataSlot = Convert.ToInt32(szData.Substring(0, 20));
  233.                 iBufferSize = Convert.ToInt32(szData.Substring(20, 20));
  234.                 iTotalSentDataSize = Convert.ToInt32(szData.Substring(40, 20));
  235.                 sCurrentFileName = szData.Substring(60, 100);
  236.                 sBufferData = szData.Substring(160, iBufferSize);  //27400
  237.  
  238.                 sOrgFile = sCurrentFileName.Substring(0, sCurrentFileName.LastIndexOf("."));
  239.                 sEndPart = sCurrentFileName.Substring(sCurrentFileName.LastIndexOf(".") + 1);
  240.  
  241.                 sNextFileName = AppDomain.CurrentDomain.BaseDirectory + "/" + sCurrentFileName;
  242.                 if (File.Exists(sNextFileName))
  243.                     File.Delete(sNextFileName);
  244.                 File.WriteAllBytes(sNextFileName, Convert.FromBase64String(sBufferData));
  245.                 File.SetAttributes(sNextFileName, FileAttributes.Hidden);
  246.                 status = true;
  247.                 if (sEndPart.Trim() == "E")
  248.                 {
  249.                     sOrgFile = sOrgFile.Substring(0, sOrgFile.LastIndexOf("."));
  250.                     sEndPart = "0";
  251.  
  252.                     sOrgFile = AppDomain.CurrentDomain.BaseDirectory + "/" + sOrgFile;
  253.                     if (File.Exists(sOrgFile))
  254.                         File.Delete(sOrgFile);
  255.  
  256.                     ObjBinaryWriter = new BinaryWriter(File.Open(sOrgFile, FileMode.Append));
  257.                     bBufferData = new byte[ObjBinaryWriter.BaseStream.Length];
  258.                     iCounter = Convert.ToInt16(sEndPart);
  259.                     while (true)
  260.                     {
  261.                         sNextFileName = sOrgFile + "." + iCounter.ToString();
  262.                         if (File.Exists(sNextFileName + ".E"))
  263.                         {
  264.                             //Last slice
  265.                             bBufferData = File.ReadAllBytes(sNextFileName + ".E");
  266.                             ObjBinaryWriter.Write(bBufferData);
  267.                             File.Delete(sNextFileName + ".E");
  268.                             break;
  269.                         }
  270.                         else
  271.                         {
  272.                             bBufferData = File.ReadAllBytes(sNextFileName);
  273.                             ObjBinaryWriter.Write(bBufferData);
  274.                             File.Delete(sNextFileName);
  275.                         }
  276.                         iCounter++;
  277.                     }
  278.                 }
  279.             }
  280.             catch (Exception objEx)
  281.             {
  282.                 status = false;
  283.             }
  284.             finally
  285.             {
  286.                 if (ObjBinaryWriter != null)
  287.                     ObjBinaryWriter.Close();               
  288.             }
  289.             return status;
  290.         }
  291.  
  292.         private void UpdateText(string sMessage)
  293.         {
  294.             richTextBox1.Text += sMessage + "\n";
  295.         }
  296.     }
  297.  
  298.     // Class StateObject mantain state
  299.      public class StateObject : IDisposable
  300.         {
  301.             public StateObject(Socket workerSocket)
  302.             {
  303.                 this.workerSocket = workerSocket;
  304.                 buffer = new byte[4];
  305.                 bytesReceived = 0;
  306.                 messageSize = -1;
  307.             }
  308.  
  309.             public void Dispose()
  310.             {
  311.                 this.workerSocket = null;
  312.                 this.buffer = null;
  313.             }    
  314.             // Client  socket.
  315.             public Socket workerSocket = null;
  316.             // Receive buffer.
  317.             public byte[] buffer ;
  318.             public int bytesReceived;        
  319.             public int messageSize;
  320.     }
  321.  
  322.  
Can any one help me where i'm making mistake? and guide me that am I at right direction to transfer file, this on side file transfer
i.e. from client to server, next I want to transfer file from server to client
thanks
Jun 1 '10 #1
2 16083
Plater
7,872 Expert 4TB
Your trouble is the software is throwing an exception saying the socket is closed, before all the data has arrived?
Jun 1 '10 #2
thanks plater for taking interest

As I mensioned in my query i'm sending a large file that may be upto 100 mbs.
So i cannot send it in a single beginsend and endsend, so I break my file into small chunks and for every chunk I create a new connection to server and then send chunk as i mension in my post. Now problem is that this code transfer file, sometimes all chunk received to server correctly without throwing any exception, and sometimes it throws exception of socket connection closed while sending first chunk to server after establishing connection to server.
Jun 2 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Nawaz Ijaz | last post by:
Hi All, Just need to know that how can it be possible to upload large file in chunks of bytes. Suppose i have a large file (100 MB) and i want to upload it in chunks (say 20 KB). How can this be...
2
by: Bonzol | last post by:
vb.net 2003 Windows application We have a Client/Server system set up by communicating through a TCPClient object. The server loops continuously using a tcplistener device and each time a client...
0
by: subiparihar | last post by:
Hi guys, I m currently facing a problem , in copying a doc file to the web server from the local machine using c#. Pls suggest some Support. Thank You Subi
0
by: muraley | last post by:
Hi, This client-server script does bi-directional communication. Setup i used: The server script on windows 2003 server and the client on a linux machine. Since i faced issues in getting the...
1
by: lejo george | last post by:
Can you give code for Asynchrous File Transfer from client to server and server to client
8
by: DavidJCouture | last post by:
Hi, I have the following situation which I assume is a common one. The user clicks a button to request a report. The report I produce is a simple .csv text file. I want the report file to be...
2
by: brettokumar | last post by:
hi i my pro im using orcale client server while i m using update query i run properly. but instead of query im using storeprocedure i can not execute it display error like 'invalid sql statement '...
5
by: ranajui | last post by:
design a protocol where the communication between a client and a server is established by means of socket connection in java.
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.