0 votes
by (8.6k points)
edited

I wonder if there's a way to measure the bytes sent or received by a connection opened by Rebex classes such as Imap without patching the Rebex source code?

Any help or suggestion on this would be greatly appreciated.

1 Answer

0 votes
by (58.9k points)
edited
 
Best answer

It is possible very well with the help of SetSocketFactory method. You just have to implement the socket factory which will create your own socket. In my example the SimpleSocket is based on Rebex ProxySocket class which is used in Rebex components and moreover it monitors the received and sent bytes.

    var imap = new Rebex.Net.Imap();
    var factory = new MySocketFactory();
    imap.SetSocketFactory(factory);

    imap.Connect("imap.gmail.com", SslMode.Implicit);

    Console.WriteLine("sent total: {0}\nreceived total: {1}", factory.BytesSent, factory.BytesReceived);

    public class MySocketFactory : ISocketFactory
    {
        /// <summary>
        /// Total bytes sent
        /// </summary>
        public long BytesSent;

        /// <summary>
        /// Total bytes received
        /// </summary>
        public long BytesReceived;

        // creates custom ISocket implementation
        ISocket ISocketFactory.CreateSocket()
        {
            return new SimpleSocket(this);
        }

        // simple ISocket implementation
        // (core functionality is taken from ProxySocket)
        private class SimpleSocket : ProxySocket, ISocket
        {
            // creator object
            private readonly MySocketFactory _factory;

            public SimpleSocket(MySocketFactory factory)
            {
                _factory = factory;
            }

            int ISocket.Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
            {
                int sent = base.Send(buffer, offset, size, socketFlags);
                _factory.BytesSent += sent;
                return sent;
            }

            int ISocket.Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
            {
                int recv = base.Receive(buffer, offset, size, socketFlags);
                _factory.BytesReceived += recv;
                return recv;
            }
        }
    }
...