I have created a TCP server. I am facing one problem. my TCP Server is not receiving data larger than 30000 bytes.
here is code to receive data
MAX_TCP_DATA = 64000
private void Process()
{
if (client.Connected == true)
{
log.InfoFormat("Client connected :: {0}", client.Client.RemoteEndPoint);
Byte[] bytes = new Byte[MAX_TCP_DATA];
String data = null;
NetworkStream stream = client.GetStream();
int i;
try
{
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// bytes contains received data in byte[].
// Translate data bytes to a UTF-8 string.
byte[] receivedBuffer = new byte[i];
Array.Copy(bytes, receivedBuffer, i);
if (log.IsDebugEnabled)
{
data = System.Text.Encoding.UTF8.GetString(receivedBuffer);
log.InfoFormat("Received MSG ::: " + data);
}
CommEventArgs comEventArg = new CommEventArgs();
comEventArg.data = receivedBuffer;
IPEndPoint remoteIPEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
comEventArg.srcAddress = remoteIPEndPoint.Address.ToString();
comEventArg.srcPort = remoteIPEndPoint.Port;
comEventArg.length = i;
this.OnDataReceived(comEventArg);
}
}
catch (Exception ex)
{
log.InfoFormat("Client disconnected : {0}", client.Client.RemoteEndPoint);
}
finally
{
client.Close();
}
}
}
when i sent byte array of 40000. my TCP Server receives only 26280 bytes.
Please tell me where is the problem in receiving.
It looks like you are trying to read all data together at once. NetworkStream is not worked as you expected. You should read the stream in small chunks and copy to the recieved buffer if you want to get all the data you expected.
In your case, you probably get 13720 bytes at first iteration and 26280 bytes at the second.
As i stated before, it should be better to read in small chunks such as 64/256/1024 bytes etc. (especially in a slow network environment).