Kel*_*ton 5 c# sockets performance networking
我正在尝试编写客户端/服务器文件传输系统.目前它的工作原理,我已经对它进行了分析,而且我似乎无法以每秒2-4兆字节的速度发送数据.我已经调整了我的代码,以便我可以以每秒数百兆字节的速度从磁盘读取数据,并且性能向导在我的磁盘读取和我的套接字写入之间没有显示1-3以上,因此我的代码已设置(它似乎)推出数据的速度和nic/cpu /主板一样快.
我想问的是,为什么不是这样的?
这是一些代码,以便您可以了解我在这里设置的内容.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想强调的是,在FileTransferer.Get_Next_Data_Chunk中几乎没有延迟,它读取速度非常快,在每秒100兆字节中.此外,套接字的WriteMessage是简化和快速的,因为我相信人性化.
也许有一个设置或什么?还是一个不同的协议?
任何想法都会受到欢迎.
我忘了提一下,这个程序是专门为LAN环境构建的,它的最大速度为1000Mbps(或者字节,我不确定,如果有人也澄清这个也很好.)
首先,您的网络速度将是每秒位数,几乎不是每秒字节数.
其次,您可能不得不通过IO读取器不断打开和关闭文件.除非您在SSD上运行,否则由于驱动器寻道时间会导致显着增加的开销.
要解决这个问题,请尝试将缓冲区大小增加到更1024小的范围.我通常使用大约262144(256K)的缓冲区大小.
除此之外,您还需要像这样管道文件IO:
ReadBlock1
loop while block length > 0
TransmitBlock1 in separate thread
ReadBlock2
Join transmit thread
end loop
Run Code Online (Sandbox Code Playgroud)
使用上述管道,您通常可以将传输速度提高一倍.
当您实现流水线文件IO时,您不再需要担心使缓冲区大小过大的问题,除非您的文件总是大小< 2 * BufferSize,因为您说您正在处理超过100mb的文件不用担心这种情况.
你可以采取的其他措施来改善这一点.
还要记住,在.NET文件中,尽管使用了线程,IO仍经常是同步的.
如需进一步阅读,请访问:http://msdn.microsoft.com/en-us/library/kztecsys.aspx
编辑:只是添加如果您认为问题是网络而不是文件IO,那么只需注释掉网络部分以使其显示即时,您获得的速度是多少?反过来怎么办,如果你让你的文件读取总是返回一个空的new byte[BufferSize],它会如何影响你的复制速度?
| 归档时间: |
|
| 查看次数: |
8008 次 |
| 最近记录: |