Moharrer
Moharrer

Reputation: 153

Socket Receive data not completed

I wrote simple socket that Send specific request to internet server and receive response but i have problem when the request sent and socket go to receive mode result of return value is not complete for example only 1075 byte of 25000 byte receive .

Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Connect(hdr.Host, 80);

byte[] req_as_bytes = Encoding.UTF8.GetBytes(RequestParam);
SentLength = skt.Send(req_as_bytes);
skt.Send(Data, SocketFlags.None);

ReturnLength = skt.Receive(Data);

skt.Shutdown(SocketShutdown.Both);
skt.Close();

but when i put a sleep before skt.recive() data complitly recive from server like this code

Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream,             ProtocolType.Tcp);
skt.Connect(hdr.Host, 80);
byte[] req_as_bytes = Encoding.UTF8.GetBytes(RequestParam);
SentLength = skt.Send(req_as_bytes);
skt.Send(Data, SocketFlags.None);

System.Threading.Thread.Sleep(4000);

ReturnLength = skt.Receive(Data);

skt.Shutdown(SocketShutdown.Both);
skt.Close();

what is the best solution for solving this problem

Upvotes: 0

Views: 2123

Answers (1)

L.B
L.B

Reputation: 116118

socket.Receive returns the number of data read. see http://msdn.microsoft.com/en-us/library/8s4y8aff.aspx

You should check ReturnLength and loop till your expected data is received.

TCP is a stream oriented protocol. You will receive the data in the order you send but it doesn't guarentee the data blocks sent and received will be equal.

Upvotes: 3

Related Questions