Can any one pls guide me through..I need to transfer the file from server to client and client to server using sockets in an Asynchronous mode so this file transfer doesn't hinder the common process of connecting and of the server and client...
here is the code i am trying to implement. this code snippet is for message transfer only for multiple clients.
/////////////////////////////file receive method when sent from client/////////////
Expand|Select|Wrap|Line Numbers
- public void OnReceive(IAsyncResult ar)
- {
- String content = String.Empty;
- // Retrieve the state object and the handler socket
- // from the asynchronous state object.
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- int bytesRead;
- if (handler.Connected)
- {
- // Read data from the client socket.
- try
- {
- bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- state.fst.Write(state.buffer, 0, bytesRead);
- state.fst.Flush();
- //There might be more data, so store the data received so far.
- // state.sb.Remove(0, state.sb.Length);
- // state.sb.Append(Encoding.ASCII.GetString(
- // state.buffer, 0, bytesRead));
- //// Display Text in Rich Text Box
- // content = state.sb.ToString();
- //SetText(content);
- handler.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0,
- new AsyncCallback(OnReceive), state);
- }
- }
- catch (SocketException socketException)
- {
- //the other side closed impolitely
- if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053)))
- {
- // Complete the disconnect request.
- String remoteIP = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
- String remotePort = ((IPEndPoint)handler.RemoteEndPoint).Port.ToString();
- // this.owner.DisconnectClient(remoteIP, remotePort);
- handler.Close();
- handler = null;
- }
- }
- catch (Exception exception)
- {
- MessageBox.Show(exception.Message + "\n" + exception.StackTrace);
- }
- }
- }
- }
- //////////class which handles connected clients on server side for file transfer for sending and receiving//////////////////////////////////
- public class StateObject
- {
- // Client socket.
- public Socket workSocket = null;
- // Size of receive buffer.
- public const int BUFFER_SIZE = 1024;
- // Receive buffer.
- public byte[] buffer = new byte[BUFFER_SIZE];
- // Received file stored in static/fixed location.
- public FileStream fst=new FileStream(@"c:\\sample1.txt",FileMode.Create,FileAccess.Write);
- //public StringBuilder sb = new StringBuilder();
- }