-1

I am working on socket C#. I've implemented a client server application using socket, but the problem is that the client doesn't receive all data sent by the server.

Here is the client application code. What should I do so that it would receive all data sent by the server?

strRecieved = "";
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
soc.Connect(endPoint);
byte[] msgBuffer = Encoding.Default.GetBytes(msgToberecieved);
soc.Send(msgBuffer, 0, msgBuffer.Length, 0);
byte[] buffer = new byte[2000];
int rec = soc.Receive(buffer);

strRecieved = String.Format(Encoding.Default.GetString(buffer));
user7394882
  • 193
  • 5
  • 17
  • " client doesn't receive all data " what do you expect to receive? and what have you received? how big is `buffer` ? – Mong Zhu Jan 11 '17 at 12:48
  • Duplicate : http://stackoverflow.com/questions/41588439/client-server-socket-c-sharp – jdweng Jan 11 '17 at 13:09
  • Possible duplicate of [Client server socket C#](http://stackoverflow.com/questions/41588439/client-server-socket-c-sharp) – FakeCaleb Jan 11 '17 at 13:18

1 Answers1

0

TCP is a streaming protocol, not a datagram protocol. This means that the data could be splitted over multiple receive-calls. It is also possible that multiple packets could be received within one receive call.

So you need a Packet Frame which should define the length of the data.

For example:

Create a header with a signatue(uint) and the datalength (uint) (so total 8 bytes). followed up with the data. (x bytes)

  • First keep receiving data until you have the size of the header. (8 bytes)
  • Check the signature if you're still aligned with the packets. (take a magic number in your case)
  • Check the value of the length if is doesn't exceed a upper bound of your receive buffer.
  • keep receiving data until you received all data.
  • handle the data.
  • repeat.

For parsing data you could use the BitConverter or the BinaryReader


Another possibility is reading data until you have a 'stop' sign. For example EOL or EOF etc.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57