A command is sent along a socket which is then 'converted' into and action with a simple switch case. If the client send the command "SENDFILE" I want the server to be able to enter a case which calls a function which then handles any further data along that socket and combines it into a file.
This is OnDataReceive callback function and switch case on the server side:
Expand|Select|Wrap|Line Numbers
- public void OnDataReceived(IAsyncResult asyn)
- {
- SocketData socketData = (SocketData)asyn.AsyncState;
- try
- {
- // Complete the BeginReceive() asynchronous call by EndReceive() method
- // which will return the number of characters written to the stream
- // by the client
- socketData.m_currentSocket.EndReceive(asyn);
- //Get packet dtata
- Packet returnPacket = Helper.ByteArrayToPacket(socketData.dataBuffer);
- switch (returnPacket.command)
- {
- case Command.SENDREQUEST: //Get ready for an incoming file
Here the class that reads from a network stream asynchronously and write to a filestream synchronously:
Is that right?
Expand|Select|Wrap|Line Numbers
- public static void NetToFile(NetworkStream net, FileStream file)
- {
- var copier = new AsyncStreamCopier(net, file);
- copier.Start();
- }
- public class AsyncStreamCopier
- {
- public event EventHandler Completed;
- private readonly Stream input;
- private readonly Stream output;
- private byte[] buffer = new byte[Settings.BufferSize];
- public AsyncStreamCopier(Stream input, Stream output)
- {
- this.input = input;
- this.output = output;
- }
- public void Start()
- {
- GetNextChunk();
- }
- private void GetNextChunk()
- {
- input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null);
- }
- private void InputReadComplete(IAsyncResult ar)
- {
- // input read asynchronously completed
- int bytesRead = input.EndRead(ar);
- if (bytesRead == 0)
- {
- RaiseCompleted();
- return;
- }
- // write synchronously
- output.Write(buffer, 0, bytesRead);
- // get next
- GetNextChunk();
- }
- private void RaiseCompleted()
- {
- if (Completed != null)
- {
- Completed(this, EventArgs.Empty);
- }
- }
- }
also because with the above example, the first time Start() is called and the function ends it goes back to the server switch case and any further (file)data is then hitting the
Expand|Select|Wrap|Line Numbers
- Packet returnPacket = Helper.ByteArrayToPacket(socketData.dataBuffer);
I previously had a synchronous method of doing it using while loops but that takes up a lot of CPU and im trying to prevent that.
Could someone point me in the right direction ? there isn't much on the net from what i can see.