Esempio n. 1
0
        private void ReceiveFunctionCallBack(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            int bytesRec = handler.EndReceive(ar);

            WriteLog(LogFormats.BytesWereSuccessfulyReceived(bytesRec, GetSocketName(handler)));

            List <byte> res = state.buffer.ToList();

            if (bytesRec < state.buffer.Length)
            {
                res.RemoveRange(bytesRec, state.buffer.Length - bytesRec);
            }

            state.receivedBytes.AddRange(res);

            if (state.allBytesCount > state.receivedBytes.Count)
            {
                int length = handler.Available > 1024 ? 1024 : handler.Available;
                state.buffer = new byte[length];

                handler.BeginReceive(state.buffer, 0, length, SocketFlags.Partial, new AsyncCallback(ReceiveFunctionCallBack), state);
            }
            else
            {
                state.function = GetDeserializedFunction(state.receivedBytes.ToArray());

                UpdateResult(state);

                Send(handler);
            }
        }
Esempio n. 2
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            int rec = handler.EndReceive(ar);

            WriteLog(LogFormats.BytesWereSuccessfulyReceived(rec, GetSocketName(handler)));

            string[] arr = Encoding.UTF8.GetString(state.buffer).Split(';');

            state.functionIndex = Convert.ToInt32(arr[0]);
            state.allBytesCount = Convert.ToInt32(arr[2]);

            int length = arr[0].Length + arr[1].Length + arr[2].Length + 3;

            if (rec > length)
            {
                state.receivedBytes = state.buffer.ToList();
                state.receivedBytes.RemoveRange(0, length);

                rec -= length;

                state.receivedBytes.RemoveRange(rec, state.receivedBytes.Count - rec);
            }

            state.buffer = new byte[1024];

            handler.BeginReceive(state.buffer, 0, state.BufferSize, SocketFlags.Partial, new AsyncCallback(ReceiveFunctionCallBack), state);
        }