المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : proper Async reading operation



C# Programming
11-06-2009, 12:40 PM
I've got a class which connects to server. Then the server sends to client at some specific time intervals data.

I've got a problem in recieving that data if single read is less than the whole data to be transfered

e.g. 10K is going to be sent. I BeginRead with 1024 buffer as in TcpClientData class with all public fields.

These are the 2 functions from the class


class MyClient
{

private void ConnectButtonClick(object sender, EventArgs e)
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ipAddress, port);
NetworkStream ns = tcpClient.GetStream();
//TcpClientData is a class with all public fields
TcpClientData cd = new TcpClientData();
cd.tcpClient = tcpClient;
cd.ms = new MemoryStream;
cd.packet = new byte[1024];
ns.BeginRead(cd.packet, 0, cd.packet.Length, new AsyncCallback(TcpClientDataReadAsyncCallback), cd);
}

private void TcpClientDataReadAsyncCallback(IAsyncResult ar)
{
TcpClientData cd = (TcpClientData)ar.AsyncState;
NetworkStream ns = cd.tcpClient.GetStream();
int sz = cd.ns.EndRead(ar);

cd.ms.Write(cd.packet, 0, sz);
while (ns.DataAvailable == true)
ns.BeginRead(cd.packet, 0, cd.packet.Length, new AsyncCallback(TcpClientDataReadAsyncCallback), cd);

//supposed that the whole data recieved
//show cd.ms.Length
//cd.ms.Length always 1024 bytes
//fails to loop in while??

//
//process that whole data from MemoryStream cd.ms
//

//keep waiting for more data on the next server data sent
cd.ms.SetLength(0);
cd.ns.BeginRead(cd.packet, 0, cd.packet.Length, new AsyncCallback(TcpClientDataReadAsyncCallback), cd);
}

}


What is wrong?

????????