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));
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.