109 lines
3.7 KiB
C#
109 lines
3.7 KiB
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace SpeedTest.Client
|
|
{
|
|
internal class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
if (args.Length < 3)
|
|
{
|
|
Console.WriteLine("Usage: SpeedTest.Client <IP> <Port> <BufferSize>");
|
|
Console.WriteLine("Example: SpeedTest.Client 127.0.0.1 8080 1024");
|
|
return;
|
|
}
|
|
|
|
if (!IPAddress.TryParse(args[0], out IPAddress? ipAddress))
|
|
{
|
|
Console.WriteLine($"Invalid IP address: {args[0]}");
|
|
return;
|
|
}
|
|
|
|
if (!int.TryParse(args[1], out int port) || port < 1 || port > 65535)
|
|
{
|
|
Console.WriteLine($"Invalid port: {args[1]}");
|
|
return;
|
|
}
|
|
|
|
if (!int.TryParse(args[2], out int bufferSize) || bufferSize <= 0)
|
|
{
|
|
Console.WriteLine($"Invalid buffer size: {args[2]}");
|
|
return;
|
|
}
|
|
|
|
TcpClient? client = null;
|
|
try
|
|
{
|
|
Console.WriteLine($"Connecting to {ipAddress}:{port}...");
|
|
client = new TcpClient();
|
|
client.Connect(ipAddress, port);
|
|
Console.WriteLine("Connected to server!");
|
|
|
|
NetworkStream stream = client.GetStream();
|
|
byte[] buffer = new byte[bufferSize];
|
|
|
|
// Fill buffer with data
|
|
for (int i = 0; i < buffer.Length; i++)
|
|
{
|
|
buffer[i] = (byte)(i % 256);
|
|
}
|
|
|
|
long bytesInCurrentSecond = 0;
|
|
bool isSending = true;
|
|
|
|
// Thread để gửi dữ liệu
|
|
Thread sendThread = new Thread(() =>
|
|
{
|
|
try
|
|
{
|
|
while (isSending)
|
|
{
|
|
stream.Write(buffer, 0, buffer.Length);
|
|
Interlocked.Add(ref bytesInCurrentSecond, buffer.Length);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Send thread error: {ex.Message}");
|
|
isSending = false;
|
|
}
|
|
});
|
|
|
|
sendThread.Start();
|
|
|
|
Console.WriteLine($"Sending data with buffer size: {bufferSize} bytes");
|
|
Console.WriteLine("Time\t\tBytes/s\t\tMB/s\t\tGB/s");
|
|
|
|
// Main thread chỉ tính toán và in kết quả
|
|
while (isSending)
|
|
{
|
|
Thread.Sleep(1000); // Đợi đúng 1 giây
|
|
|
|
long bytesThisSecond = Interlocked.Exchange(ref bytesInCurrentSecond, 0);
|
|
|
|
double bytesPerSecond = bytesThisSecond;
|
|
double mbPerSecond = bytesPerSecond / (1024.0 * 1024.0);
|
|
double gbPerSecond = bytesPerSecond / (1024.0 * 1024.0 * 1024.0);
|
|
|
|
Console.WriteLine($"{DateTime.Now:HH:mm:ss}\t{bytesPerSecond:N0}\t\t{mbPerSecond:F2}\t\t{gbPerSecond:F4}");
|
|
}
|
|
|
|
sendThread.Join();
|
|
}
|
|
catch (SocketException ex)
|
|
{
|
|
Console.WriteLine($"Socket error: {ex.Message}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error: {ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
client?.Close();
|
|
}
|
|
}
|
|
}
|
|
}
|