示例#1
0
        private void recieveCallback(IAsyncResult ar)
        {
            log($"Data from Client: {id} recieved.");

            try
            {
                packageState package = ar.AsyncState as packageState;
                Socket       clientS = package.socket;

                int bytesRead = clientS.EndReceive(ar);

                if (bytesRead > 0)
                {
                    int size = ATserver.BUFFER_SIZE;
                    if (package.readOffset == -1)
                    {
                        size = BitConverter.ToInt32(package.sizeBuffer, 0);
                        package.readBuffer = new byte[size];
                        package.readOffset = 0;
                    }
                    else
                    {
                        package.readOffset += bytesRead;

                        if (package.readOffset == package.readBuffer.Length)
                        {
                            //clone array so the package can be disposed
                            byte[] temp = package.readBuffer.Clone() as byte[];

                            //invoke the event
                            recievingData?.Invoke(this.id, temp);

                            //free memory
                            package.Dispose();
                            package = new packageState(clientS);
                        }
                    }

                    if (package.readBuffer == null)
                    {
                        package.socket.BeginReceive(package.sizeBuffer, 0, package.sizeBuffer.Length, SocketFlags.None, new AsyncCallback(recieveCallback), package);
                    }
                    else
                    {
                        int readsize = (ATserver.BUFFER_SIZE > size) ? size : ATserver.BUFFER_SIZE;
                        package.socket.BeginReceive(package.readBuffer, package.readOffset, readsize, SocketFlags.None, new AsyncCallback(recieveCallback), package);
                    }
                }
                else
                {
                    log("Error recieving Message! ReadBytes < 0.");
                    closeClient();
                }
            }
            catch
            {
                log("Error recieving Message!");
                closeClient();
            }
        }
示例#2
0
        public void startClient()
        {
            packageState package = new packageState(this.socket);

            socket.BeginReceive(package.sizeBuffer, 0, package.sizeBuffer.Length, SocketFlags.None, new AsyncCallback(recieveCallback), package);

            log($"Client: {id} is set up.");
        }