大转移期间的插座失速

时间:2014-06-03 12:13:51

标签: c# .net sockets

我目前正在使用.net套接字处理文件tranfert程序,但我遇到了一个问题: 当我试图转移大量数据时(~2Mo),我接收套接缝“停止”。我出于各种原因发送我的文件(~10ko)

这是我的启发码(在我的客户端套接字上):

public ClientSocket(string _IP, int _port)
    {
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        this.IP = _IP;
        this.port = _port;
        StateObject so = new StateObject(clientSocket);
        this.clientConnection = new ClientConnection(so);
        Logs.Print(Logs.LogType.INFO, "Tentative de connexion à " + this.IP + ":" + this.port);
        try
        {
            so.socket.Connect(IPAddress.Parse(this.IP), this.port);
            Logs.Print(Logs.LogType.INFO, "Connecté à " + this.IP + ":" + this.port);
            so.socket.BeginReceive(so.buffer, 0, StateObject.bufferSize, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), so);                
        }
        catch (SocketException ex)
        {
            Logs.Print(Logs.LogType.ERROR, "Erreur lors de la connexion : Code " + ex.ErrorCode + " | Message : " + ex.Message);
        }
    }
private void ReceiveCallback(IAsyncResult asyncResult)
    {
        StateObject so = (StateObject)asyncResult.AsyncState;
        int read = so.socket.EndReceive(asyncResult);
        Logs.Print(Logs.LogType.DEBUG, "Réception de " + read + " Octets");
        // Transfert du buffer primaire au buffer de stockage secondaire
        for (int i = 0; i < read; i++)
            so.subBuffer.Enqueue(so.buffer[i]);

        uint dataUsed = this.clientConnection.Receive(so.subBuffer);
        for (uint i = 0; i < dataUsed; i++)
            so.subBuffer.Dequeue();
        so.socket.BeginReceive(so.buffer, 0, StateObject.bufferSize, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), so);
    }

我使用存储对象“StateObject”来保持对套接字的引用,并且每次调用receivecallback时都会访问缓冲区被清空的接收缓冲区数组和子缓冲区。

这是我的发件人代码(在我的服务器套接字上):

public void Send(int id, DataContainer dataContainer)
{
        Packet[] packets = this.ClientsSockets[id].Send(dataContainer);
        for (int i = 0; i < packets.Length; i++)
        {
            Logs.Print(Logs.LogType.DEBUG, "Envoi de " + packets[i].ToBinary().Length + " octets");

            this.ClientsSockets[id].stateObject.socket.Send(packets[i].ToBinary());
        }
    }

你们有没有遇到过这种问题?

0 个答案:

没有答案