我是编程新手。对于我的第一个应用,我决定创建两个控制台应用程序 - 服务器和客户端应用我想在客户端和服务器应用程序之间测试数据事务带宽(顺便说一下我使用的是套接字)。我的问题是我需要测试连接速度,比方说10秒,然后在那10秒后我需要获得接收的数据量(我在这个时间段内收到的)并计算速度......我该怎么办?是什么?
客户端应用
namespace Example_01_Sockets_Client
{
class MainClass
{
public static void Main(string[] args)
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ownAddress = IPAddress.Parse("127.0.0.1");
var ownEndpoint = new IPEndPoint(ownAddress, 4321);
socket.Bind(ownEndpoint);
Console.WriteLine();
Console.WriteLine("Trying to connect to server...");
var serverAddress = IPAddress.Parse("127.0.0.1");
socket.Connect(serverAddress, 2222);
Console.WriteLine("Connected to server");
var buffer = new byte[1024 * 150000];
socket.ReceiveTimeout = 100;
int receivedBytesLen = socket.Receive(buffer);
Console.WriteLine("Download speed: " + ((receivedBytesLen) / 100 + "kb/s ") );
Console.WriteLine("Press any key to exit");
Console.ReadKey();
socket.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
服务器应用
class MainClass
{
public static void Main(string[] args)
{
bool exit = false;
while (!exit)
{
var listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 2222);
listeningSocket.Bind(localEndpoint);
listeningSocket.Listen(1);
Console.WriteLine();
Console.WriteLine("Waiting for client...");
Socket connectedSocket = listeningSocket.Accept();
listeningSocket.Close();
string clientAddress = connectedSocket.RemoteEndPoint.ToString();
Console.WriteLine("Client connected (" + clientAddress + ")");
string fileName = "downTest.txt";
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileData = File.ReadAllBytes(fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
connectedSocket.Send(fileData);
//int bytesReceived = connectedSocket.Receive();
Console.WriteLine("Client connected (" + clientAddress + ")");
connectedSocket.Close();
}
}
}
感谢您的帮助!!!
答案 0 :(得分:1)
为什么不使用一定数量的数据(例如4,096kb)。在开始在客户端上下载数据之前,使用Stopwatch类启动计时器,然后在完成发送后立即停止计时器。然后,您可以使用“已用时间”属性来确定发送固定数量的数据所需的时间。
Stopwatch timer = new Stopwatch();
timer.Start();
// Download data here
timer.Stop();
int elapsedTime = timer.Elapsed.TotalSeconds;