I have built a server that receives requests from a client and gives a response that depends on the request Type. If the request type is streaming, the server must send data array. While the server's streaming data the client may send a stop request to stop the streaming. If the request and the response is transferred on the same TCP connection the server only receives the stop request when all the data has finished streaming to the client. I think I must use Asynchronous write to solve this problem. This is my code:
First I create a loop back to receive connection from clients:
while (!done)
{
try
Socket socket = listener.AcceptSocket();
ClientInteraction clIr = new ClientInteraction(socket, statusList);
Thread thread = new Thread(new ThreadStart(clIr.Process));
thread.Start();
}
catch (Exception ex)
Console.WriteLine(ex.ToString());
In Process function of ClientInteraction class :
Public void Process()
ns = new NetworkStream(socket);
while (true)
this.myReadBuffer = new byte[socket.ReceiveBufferSize];
this.numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);
catch
break;
if (numberOfBytesRead == 0)
else
HandleRequest(myReadBuffer, numberOfBytesRead);
In HandleRequest Function, if request's STREAM, I will send data in an array to client:
Public void HanldeRequest(……)
myCompleteMessage = "";
myCompleteMessage =
String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
If(myCompleteMessage == "Stream")
//I get data and call SendData function
foreach(.......)
//get data
........
SendData(data);
public void SendData(byte[] data)
//ns.Write(data, 0, data.Length);
ns.BeginWrite(data, 0, data.Length, new AsyncCallback(StreamData), null);
public void StreamData(IAsyncResult asynResult)
if(asynResult != null)
ns.EndWrite(asynResult);