【发布时间】:2011-11-30 04:44:35
【问题描述】:
我正在尝试编写一个客户端/服务器文件传输系统。目前它可以工作,并且我已经对其进行了分析,而且我似乎无法以每秒 2-4 兆字节的速度发送数据。 我已经调整了我的代码,以便我可以以每秒数百兆字节的速度从磁盘读取数据,并且性能向导在我的磁盘读取和我的套接字写入之间没有显示超过 1-3,所以我的代码已设置(它似乎)以尽可能快的速度推出数据,只要 nic/cpu/motherboard 可以处理它。
我想问题是,为什么不是这样?
这是一些代码,以便您了解我在这里设置了什么。
套接字代码(尽可能精简)
namespace Skylabs.Net.Sockets
{
public abstract class SwiftSocket
{
public TcpClient Sock { get; set; }
public NetworkStream Stream { get; set; }
public const int BufferSize = 1024;
public byte[] Buffer = new byte[BufferSize];
public bool Connected { get; private set; }
private Thread _thread;
private bool _kill = false;
protected SwiftSocket()
{
Connected = false;
Sock = null;
_thread = new Thread(Run);
}
protected SwiftSocket(TcpClient client)
{
_Connect(client);
}
public bool Connect(string host, int port)
{
if (!Connected)
{
TcpClient c = new TcpClient();
try
{
c.Connect(host, port);
_Connect(c);
return true;
}
catch (SocketException e)
{
return false;
}
}
return false;
}
public void Close()
{
_kill = true;
}
private void _Connect(TcpClient c)
{
Connected = true;
Sock = c;
Stream = Sock.GetStream();
_thread = new Thread(Run);
_thread.Name = "SwiftSocketReader: " + c.Client.RemoteEndPoint.ToString();
_thread.Start();
}
private void Run()
{
int Header = -1;
int PCount = -1;
List<byte[]> Parts = null;
byte[] sizeBuff = new byte[8];
while (!_kill)
{
try
{
Header = Stream.ReadByte();
PCount = Stream.ReadByte();
if (PCount > 0)
Parts = new List<byte[]>(PCount);
for (int i = 0; i < PCount; i++)
{
int count = Stream.Read(sizeBuff, 0, 8);
while (count < 8)
{
sizeBuff[count - 1] = (byte)Stream.ReadByte();
count++;
}
long pieceSize = BitConverter.ToInt64(sizeBuff, 0);
byte[] part = new byte[pieceSize];
count = Stream.Read(part, 0, (int)pieceSize);
while (count < pieceSize)
{
part[count - 1] = (byte)Stream.ReadByte();
}
Parts.Add(part);
}
HandleMessage(Header, Parts);
Thread.Sleep(10);
}
catch (IOException)
{
Connected = false;
if(System.Diagnostics.Debugger.IsAttached)System.Diagnostics.Debugger.Break();
break;
}
catch (SocketException)
{
Connected = false;
if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
break;
}
}
HandleDisconnect();
}
public void WriteMessage(int header, List<byte[]> parts)
{
try
{
byte[] sizeBuffer = new byte[8];
//Write header byte
Stream.WriteByte((byte)header);
if (parts == null)
Stream.WriteByte((byte)0);
else
{
Stream.WriteByte((byte)parts.Count);
foreach (byte[] p in parts)
{
sizeBuffer = BitConverter.GetBytes(p.LongLength);
//Write the length of the part being sent
Stream.Write(sizeBuffer, 0, 8);
Stream.Write(p, 0, p.Length);
//Sock.Client.Send(p, 0, p.Length, SocketFlags.None);
}
}
}
catch (IOException)
{
if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
_kill = true;
}
catch (SocketException)
{
if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
_kill = true;
}
}
protected void WriteMessage(int header)
{
WriteMessage(header,null);
}
public abstract void HandleMessage(int header, List<byte[]> parts);
public abstract void HandleDisconnect();
}
}
文件传输器代码(设置套接字、加载文件等的类)
namespace Skylabs.Breeze
{
public class FileTransferer
{
public String Host { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public string Hash { get; set; }
public FileStream File { get; set; }
public List<TransferClient> Clients { get; set; }
public const int BufferSize = 1024;
public int TotalPacketsSent = 0;
public long FileSize{get; private set; }
public long TotalBytesSent{get; set; }
private int clientNum = 0;
public int Progress
{
get
{
return (int)(((double)TotalBytesSent / (double)FileSize) * 100d);
}
}
public event EventHandler OnComplete;
public FileTransferer()
{
}
public FileTransferer(string fileName, string host)
{
FilePath = fileName;
FileInfo f = new FileInfo(fileName);
FileName = f.Name;
Host = host;
TotalBytesSent = 0;
try
{
File = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan);
File.Lock(0,File.Length);
}
catch (Exception e)
{
ErrorWindow er = new ErrorWindow(e);
er.ShowDialog();
}
}
public bool Grab_Next_Data_Chunk(ref byte[] buffer, out int size, out long pos)
{
lock (File)
{
pos = File.Position;
size = 0;
if (pos >= FileSize - 1)
return false;
int count = File.Read(buffer, 0, (FileSize - pos) >= FileTransferer.BufferSize ? FileTransferer.BufferSize : (int)(FileSize - pos));
//TotalBytesSent += count;
size = count;
TotalPacketsSent++;
return true;
}
}
public bool Start(int ConnectionCount)
{
Program.ServerTrace.TraceInformation("Creating Connections.");
if (Create_Connections(ConnectionCount) == false)
{
return false;
}
File.Seek(0, SeekOrigin.Begin);
FileSize = File.Length;
Clients[0].Start(this,0);
List<byte[]> parts = new List<byte[]>(1);
parts.Add(BitConverter.GetBytes(FileSize));
Clients[0].WriteMessage((int)Program.Message.CFileStart, parts);
Program.ServerTrace.TraceInformation("Sent start packet");
for (clientNum = 1; clientNum < ConnectionCount; clientNum++)
{
Clients[clientNum].Start(this, clientNum);
}
return true;
}
private bool Create_Connections(int count)
{
Clients = new List<TransferClient>();
for (int i = 0; i < count; i++)
{
TransferClient tc = new TransferClient();
if (tc.Connect(Host, 7678) == false)
return false;
Clients.Add(tc);
}
return true;
}
public void AddClient()
{
TransferClient tc = new TransferClient();
tc.Connect(Host, 7678);
tc.Start(this, clientNum);
clientNum++;
Clients.Add(tc);
}
public void RemoveClient()
{
Clients.Last().Kill();
}
public void AdjustClientCount(int newCount)
{
int dif = newCount - Clients.Count;
if (dif > 0)
{
for(int i=0;i<dif;i++)
AddClient();
}
else
{
for(int i=0;i<Math.Abs(dif);i++)
RemoveClient();
}
}
public void ClientDone(TransferClient tc)
{
List<byte[]> parts = new List<byte[]>(1);
parts.Add(ASCIIEncoding.ASCII.GetBytes(FileName));
tc.WriteMessage((int)Program.Message.CPartDone,parts);
tc.Close();
Clients.Remove(tc);
if (Clients.Count == 0)
{
Program.ServerTrace.TraceInformation("File '{0}' Transfered.\nTotal Packets Sent: {1}", FilePath,
TotalPacketsSent);
File.Unlock(0,File.Length);
File.Close();
File.Dispose();
if(OnComplete != null)
OnComplete.Invoke(this,null);
}
}
}
public class TransferClient : Skylabs.Net.Sockets.SwiftSocket,IEquatable<TransferClient>
{
public FileTransferer Parent;
public int ID;
private bool KeepRunning = true;
public Thread Runner;
public void Start(FileTransferer parent, int id)
{
this.Sock.Client.
Parent = parent;
ID = id;
List<byte[]> p = new List<byte[]>(1);
p.Add(Encoding.ASCII.GetBytes(Parent.FileName));
WriteMessage((int)Program.Message.CHello, p);
}
public void Kill()
{
KeepRunning = false;
}
private void run()
{
while (KeepRunning)
{
List<Byte[]> p = new List<byte[]>(3);
byte[] data = new byte[FileTransferer.BufferSize];
int size = 0;
long pos = 0;
if (Parent.Grab_Next_Data_Chunk(ref data,out size,out pos))
{
p.Add(data);
p.Add(BitConverter.GetBytes(size));
p.Add(BitConverter.GetBytes(pos));
WriteMessage((int)Program.Message.CData, p);
Parent.TotalBytesSent += size;
}
else
{
break;
}
Thread.Sleep(10);
}
Parent.ClientDone(this);
}
public bool Equals(TransferClient other)
{
return this.ID == other.ID;
}
public override void HandleMessage(int header, List<byte[]> parts)
{
switch (header)
{
case (int)Program.Message.SStart:
{
Runner = new Thread(run);
Runner.Start();
break;
}
}
}
public override void HandleDisconnect()
{
//throw new NotImplementedException();
}
}
}
我想强调的是,在 FileTransferer.Get_Next_Data_Chunk 中几乎没有延迟,它的读取速度非常快,每秒 100 兆字节。 此外,我相信套接字的 WriteMessage 是流线型和快速的。
也许有一个设置或什么?还是不同的协议?
欢迎提出任何想法。
我忘了提一下,这个程序是专门为 LAN 环境构建的,它的最大速度为 1000Mbps(或字节,我不确定,如果有人能澄清这一点,那也很好。)
【问题讨论】:
-
嗯,有一个显而易见的问题:您的网络有多快?发布一些 iperf 结果,因为它们代表了您应该希望接近的上限。
-
您忘记删除
Thread.Sleep(10);?如果您只是想让其他线程有机会运行,请执行Thread.Sleep(0)。 -
我会重新考虑其中一些公共可变属性。
-
另外,如果你真的希望它尽可能快,请使用 UDP 而不是 TCP,但你必须确认接收到的数据确实是正确的。通常一个 MD5 或其他一些哈希是可以的。阅读 bittorrent 协议。
-
您也可以尝试在发送前将
List<byte[]>转换为单个byte[],否则您最终可能会发送小数据包。
标签: c# performance sockets networking