c# slow socket 速度

标签 c# performance sockets 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();

    }
}

File Transferer 代码(设置套接字、加载文件等的类)

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 中几乎没有延迟,它的读取速度非常快,每秒数百兆字节。 此外,我认为套接字的 WriteMessage 是流线型和快速的。

也许有什么设置?还是不同的协议(protocol)?

我们非常欢迎任何想法。

我忘了说,这个程序是专门为 LAN 环境构建的,它的最大速度为 1000Mbps(或字节,我不确定,如果有人也能澄清这一点,那也很好。)

最佳答案

首先,您的网络速度将是每秒比特数,几乎不是每秒字节数。

其次,您可能会受到 IO 阅读器不断打开和关闭文件的限制。除非您在 SSD 上运行,否则由于驱动器寻道时间,这将导致开销显着增加。

要解决这个问题,请尝试将缓冲区大小增加到更大的值 1024很小。我通常使用 262144 左右(256K) 用于我的缓冲区大小。

除此之外,您还需要像这样管道化文件 IO:

ReadBlock1
loop while block length > 0
    TransmitBlock1 in separate thread
    ReadBlock2
    Join transmit thread
end loop

使用上述管道,您通常可以将传输速度提高一倍。

当您实现流水线文件 IO 时,您不再需要担心缓冲区大小过大的问题,除非您的文件总是大小为 < 2 * BufferSize。 ,因为您说您正在处理超过 100mb 的文件,所以您不必担心这种情况。

您可以做的其他改进是使用 .

还要记住,在 .NET 中,尽管使用了线程,文件 IO 通常是同步的。

如需进一步阅读,请参阅:http://msdn.microsoft.com/en-us/library/kztecsys.aspx

编辑:只是补充一下,如果您认为问题出在网络而不是文件 IO,那么只需注释掉网络部分,使其立即出现,那么您的速度是多少?反过来呢,如果你让你的文件读取总是返回一个空的new byte[BufferSize]怎么办?这对您的复制速度有何影响?

关于c# slow socket 速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321271/

相关文章:

c# - 无法通过 WCFTestClient 测试自托管 WCF 服务

java - 使用socket编程将文件从android传输到pc

sockets - 在 Go 中实现 ICMP ping

C# - winform - 如何在 app.config 中加密端点地址

c# - 对同一个任务多次等待可能会导致阻塞

performance - Java 是否将 new HashSet(someHashSet).contains() 优化为 O(1)?

performance - ext-all.js VS ext-all-debug.js

c - 如何在C中的Excel工作表中创建另一行

c# - 可用 UWP 菜单控件之间的差异

sql - 聚合还是不聚合,这是数据库模式设计的问题