我有以下代码,每秒向连接的TCP客户端发送八个图像:
static void HandleServer()
{
Console.WriteLine("Server is starting...");
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
newclient.Address, newclient.Port);
HandleImage(client, newsock);
}
private static void HandleImage(Socket client, Socket s)
{
int sent;
int imageCount = 0;
double totalSize = 0;
try
{
while (true)
{
Image bmp = getImage();
MemoryStream ms = new MemoryStream();
// Save to memory using the bmp format
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bmpBytes = ms.ToArray();
bmp.Dispose();
ms.Close();
sent = SendVarData(client, bmpBytes);
imageCount++;
totalSize += sent;
Console.WriteLine("Sent " + sent + " bytes");
Thread.Sleep(125);
}
}
catch (Exception e)
{
Console.WriteLine("Exception catched, probably an interrupted connection. Restarting server...");
s.Close();
Console.WriteLine("Transferred {0} images with a total size of {1}", imageCount, totalSize);
Console.WriteLine("Average JPEG size: " + totalSize / imageCount + " byte");
HandleServer();
}
}
private static int SendVarData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);
while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
}
}
每个图像的平均大小为0.046兆字节,这使我每秒计算8张图像的网络带宽为0.37兆字节。 我在Windows 10任务管理器中监控了应用程序,发现在两到三秒钟后网络使用率上升到35-40 Mbps。 可以和我的源代码一起使用吗?
非常感谢