在C#中,使用TcpClient傳輸大數據量時,可以采用以下技巧來優化性能和可靠性:
int bufferSize = 4096; // 可根據實際情況調整
byte[] buffer = new byte[bufferSize];
int bytesRead;
using (TcpClient client = new TcpClient())
{
client.Connect(ipAddress, port);
using (NetworkStream stream = client.GetStream())
{
while ((bytesRead = inputStream.Read(buffer, 0, bufferSize)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
}
private async Task SendDataAsync(TcpClient client, Stream inputStream)
{
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesRead;
using (NetworkStream stream = client.GetStream())
{
while ((bytesRead = await inputStream.ReadAsync(buffer, 0, bufferSize)) > 0)
{
await stream.WriteAsync(buffer, 0, bytesRead);
}
}
}
TcpClient client = new TcpClient();
client.ReceiveTimeout = 5000; // 設置接收超時時間為5秒
client.SendTimeout = 5000; // 設置發送超時時間為5秒
int retryCount = 3;
bool success = false;
while (retryCount > 0 && !success)
{
try
{
using (TcpClient client = new TcpClient())
{
client.Connect(ipAddress, port);
using (NetworkStream stream = client.GetStream())
{
// 發送和接收數據
success = true;
}
}
}
catch (Exception ex)
{
retryCount--;
Console.WriteLine($"Error: {ex.Message}. Retry count: {retryCount}");
}
}
using (TcpClient client = new TcpClient())
{
client.Connect(ipAddress, port);
using (NetworkStream stream = client.GetStream())
{
using (GZipStream compressionStream = new GZipStream(stream, CompressionMode.Compress))
{
// 發送和接收數據
}
}
}
通過以上技巧,可以在C#中使用TcpClient高效地傳輸大數據量。