Click here to Skip to main content
13,094,983 members (80,923 online)
Click here to Skip to main content
Add your own
alternative version


35 bookmarked
Posted 25 Oct 2005

Glue internet information server with your business logical tier using batching, asynchrony, and parallel computation

, 25 May 2006
Rate this:
Please Sign up or sign in to vote.
A great and unusual way to boost your web application performance and scalability five times or more

1.    Introduction<?xml:namespace prefix = o /><o:p>

        By this time, N-tier applications (distributed applications) have become the norm for building enterprise software. In essence, an N-tier application consists of a number software parts running within different machines. To achieve such a distribution, data communications among these machines are critical for all real enterprise software. I created a framework, named as SocketPro, to glue all of software parts across different machines with batching, asynchrony and parallel computation using non-blocking socket. Recently, I have read an article entitled as Asynchronous Pages in ASP.Net 2.0. This article is very interesting to me, and leads me to think how to integrate SocketPro with ASP.NET for developing high performance web application based on batching and asynchrony computation using a pool of pre-opened sockets and database objects.

2.   Client and server setups<o:p>

Client setup:<o:p>

To play with this provided sample, you need to register two COM dlls, usocket.dll and udb.dll within SocketPro after you download it from Additionally, you need to get dotNet framework version 2.0, and Visual studio 2005 installed.

Server setup:<o:p>

See the link here. Make sure that RemoteConnector.exe runs properly. Afterwards, follow the guide and make sure that uodbsvr.dll is loaded into the application RemoteConnector.exe. This sample is running against with MS Access sample database Northwind. If you don’t use the database, you can go to the provided source file and modify OLEDB connection string to whatever database you have. Note you don’t have to install any dotNet components because the sample server application doesn’t dependent on dotNet.

3.   Brief introduction to socket pool<o:p>

      A socket pool, similar to a thread pool, contains a number of sockets running within a few threads. Each of threads supports a few sockets. Socket pool manages required threads and contained sockets internally. The socket pool is created for supporting thousands of web/client requests from different machines. When an application starts, it pre-creates a pool of sockets that are connected to a remote host. Afterwards, we can bind an opened socket with one or more objects. Those objects use their bound sockets to process all of their requests. See the following Figure 1.

<?xml:namespace prefix = v /><v:shapetype id=_x0000_t75 stroked="f" filled="f" path="m@4@5l@4@11@9@11@9@5xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600"><v:stroke joinstyle="miter"><v:formulas><v:f eqn="if lineDrawn pixelLineWidth 0"><v:f eqn="sum @0 1 0"><v:f eqn="sum 0 0 @1"><v:f eqn="prod @2 1 2"><v:f eqn="prod @3 21600 pixelWidth"><v:f eqn="prod @3 21600 pixelHeight"><v:f eqn="sum @0 0 1"><v:f eqn="prod @6 1 2"><v:f eqn="prod @7 21600 pixelWidth"><v:f eqn="sum @8 21600 0"><v:f eqn="prod @7 21600 pixelHeight"><v:f eqn="sum @10 21600 0"><v:path o:connecttype="rect" gradientshapeok="t" o:extrusionok="f"><o:lock aspectratio="t" v:ext="edit">Sample screenshot 

Figure 1: A socket pool contains six sockets hosted within three threads.<o:p>

      Like a thread pool, we can use a limited number of sockets shared by different requests. When a client sends a request, we first lock a socket and its bound objects, and send all your requests in one batch to a remote host. When a remote host processes all of them and returns their results back, we can unlock the socket and its bound objects, and release all of then as one unit back into the pool. As you can see, we can avoid creating sockets and objects and building connections repeatedly so that an application performance and scalability are significantly improved using a small amount of pre-allocated resource.

4.   Incredibly easy and simple to integrate SocketPro with ASP.Net 2.0 asynchronous pages<o:p>

      SocketPro is written from asynchrony computation that enables us to integrate various objects with asynchronous pages very easily. Let us see how simple code can be.

A.  Start a pool of sockets and bind objects one time only.

        protected void StartProcessing()<o:p>


                bool bInit = CDBHandler.IsInit;<o:p>

                if (!bInit)<o:p>


                        //Start a pool of sockets running in asynchronous mode.<o:p>

                        //Each of sockets is bound with one opened UDataSource, one opened USession, One opened UComamnd and one URowset.<o:p>

                        //All of 6 sockets with three threads are connected to a remote SocketPro server forever.<o:p>

                        bInit = CDBHandler.InitDBPool(<o:p>

                                                3, //the number of threads<o:p>

                                                2, //the number of sockets per thread<o:p>

                                                "localhost", //a remote host address like, or MyServerName<o:p>

                                                17001, //a port number<o:p>

                                                "SocketPro", //a user id<o:p>

                                                "PassOne", // a passowrd<o:p>

                                                "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\NWIND3.mdb" <o:p>

                                                //an OLEDB connection string to a backend database<o:p>



                if (bInit)<o:p>


                        //register ASP.NET 2 methods for processing requests asynchrnously.<o:p>

                        AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));<o:p>




        protected void btnExecuteSQL_Click(object sender, EventArgs e)<o:p>




      When a request comes, it kicks the function StartProcessing. Inside the function, it starts a pool of sockets and bind the pool with a set of database objects. It happens only one time after an application starts. Afterwards, the pool runs forever and we will never create any new sockets or objects. Also, we will never build a socket connection again.<o:p>

      B.   Send all of requests in one batch.<o:p>

IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)<o:p>


                //must lock a socket and its bound UDataSource, USession, UComamnd and URowset <o:p>

                //objects first from the socket pool.<o:p>

                m_DBHandler = CDBHandler.LockDBHandler(cb);<o:p>

                if (m_DBHandler != null)<o:p>


                        //batch any number of requests together.<o:p>



                        m_DBHandler.ExecuteQuery(idQueryOne.Text, "Orders", 0, 0);<o:p>


                        CParamInfo[] aParamInfo = new CParamInfo[2];<o:p>

                        aParamInfo[0] = new CParamInfo();<o:p>

                        aParamInfo[1] = new CParamInfo();<o:p>

                        aParamInfo[0].m_sDBType = (short)UDBLib.tagSockDataType.sdVT_R8;<o:p>

                        aParamInfo[1].m_sDBType = (short)UDBLib.tagSockDataType.sdVT_R8;<o:p>

                        m_DBHandler.OpenCommandWithParameters("Select * from Products Where UnitPrice between ? and ?", aParamInfo);<o:p>


                        object[] aData = new object[2];<o:p>

                        aData[0] = double.Parse(txtPriceMin.Text);<o:p>

                        aData[1] = double.Parse(txtPriceMax.Text);<o:p>


                        //open rowset with a set of parameters<o:p>

                        m_DBHandler.OpenQueryFromParameters(aData, "Products", 0, 0);<o:p>


                        //Of course, you can batch more requests here.<o:p>


                        //true -- informs the remote socketpro server to return all of returned results in batches<o:p>

                        m_DBHandler.Socket.CommitBatching(true); <o:p>


                        //At this moment, all of requests are sent to a remote server for processing in one batch.<o:p>


                return m_DBHandler;<o:p>


      We starts locking a DB handler that represents a socket and a set of its bound database objects like data source, session, command and rowset. Once getting the handler, we batch all requests and send them to remote for processing without waiting for return results for deleting a number of records and creating a DataSet containing two tables. This step is truly very fast.<o:p>

      C.  Bind tables with web DataGrid controls when all of requests are processed and returned. Here is the code:<o:p>

void EndAsyncOperation(IAsyncResult ar)<o:p>


                DataTable dt;<o:p>

                //At this moment, all of requests are processed and returned.<o:p>

                //binding data<o:p>

                dt = m_DBHandler.DataSet.Tables["Orders"];<o:p>

                gvQueryOne.DataSource = dt;<o:p>


                dt = m_DBHandler.DataSet.Tables["Products"];<o:p>

                gvQueryTwo.DataSource = dt;<o:p>


                //After this function is called, <o:p>

                //CDBHandler will automatically unlock its socket and DB objects,<o:p>

                //and release those objects back into pool for reuse by a new page.<o:p>


      That is all you need to create an asynchronous web page. As said before, we need to unlock a socket and its bound database objects. However, I don’t find the code to unlock a previously locked DB handler. Why? Actually, CDBHandler automatically releases those objects and socket back into pool for reuse when it finds that all of batched requests are processed and returned.<o:p><o:p>

5.   Understanding implementation of class CDBHandler and extending it as you need<o:p>

      CBHandler wraps one socket and four OLEDB database objects, data source, session, command and rowset. It implements the interface IAsyncResult. CDBHandler uses USocketPool COM object (usocket.dll) to manage a pool of sockets. See the below code:<o:p><o:p>

     m_SocketPool = new USocketPoolClass();<o:p>

m_SocketPool.StartPool(bThreads, bSocketsPerThread);<o:p>

m_SocketPool.ConnectAll(strHost, nPort, (int)USOCKETLib.tagServiceID.sidOleDB, strUID, strPassword, sEncryptionMethod, bZip);<o:p>

      Once a socket pool is started, we conect all of sockets onto a remote host with a initial remote service indicated by a server id as shown above. However, at this time there is no database connection established between a romote server and a backend database. To bind CDBHandler to a backend database, we use remote database service component udb.dll at client side and component uodbsvr.dll at server side as described in the Section 2. First of all, we create four client database objects and set up events for each of the four database objects. <o:p>

m_Command = new UCommandClass();<o:p>

   m_Rowset = new URowsetClass();<o:p>

   m_DataSource = new UDataSourceClass();<o:p>

   m_Session = new USessionClass();<o:p>

   m_DataSource.OnRequestProcessed += new _IURequestEvent_OnRequestProcessedEventHandler(OnDataSourceRequestProcessed);<o:p>

   m_Session.OnRequestProcessed += new _IURequestEvent_OnRequestProcessedEventHandler(OnSessionRequestProcessed);<o:p>

   m_Command.OnRequestProcessed += new _IURequestEvent_OnRequestProcessedEventHandler(OnCommandRequestProcessed);<o:p>

   m_Rowset.OnRequestProcessed += new _IURequestEvent_OnRequestProcessedEventHandler(OnRowsetRequestProcessed);<o:p>

      Once we get an interface to a socket, we can attach all of four database objects to the socket by the following code. Additionally, we can subscribe an event on the socket level to monitor all of requests processed.<o:p>

      private bool AttachSocket(USocketClass ClientSocket)<o:p>


                if (ClientSocket == null)<o:p>

                        return false;<o:p>





                m_ClientSocket = ClientSocket;<o:p>

                m_ClientSocket.OnRequestProcessed += new _IUSocketEvent_OnRequestProcessedEventHandler(OnAllRequestProcessed);<o:p>

                return true;<o:p>


      Here is this way how to find a socket from a socket pool and bind it with the four database objects. Basically, we lock a socket first and get a socket interface. Afterwards, attach four database objects with the socket and connect to a backend database through the socket server. At last, we unlock it and the socket is ready for reuse in socket pool. Note that the code below also increase sending and receiving buffer sizes for both client and server sockets. This will increase data output speed if your network bandwidth is 100 mbps or over.<o:p>

      private static bool BindDBhandlerWithSocket(string strDBConnectionString, int nIOBufferSize)<o:p>


                int n;<o:p>

                for (n = 0; n < m_SocketPool.ConnectedSockets; n++)<o:p>


                        USocketClass ClientSocket = (USocketClass)m_SocketPool.LockASocket(0, null);<o:p>

                        if (ClientSocket != null)<o:p>


                                CDBHandler DBHandler = new CDBHandler();<o:p>


                                if (DBHandler.ConnectDB(strDBConnectionString))<o:p>



                                        if (nIOBufferSize > 5 * 1460)<o:p>


                                                ClientSocket.SetSockOpt((int)USOCKETLib.tagSocketOption.soRcvBuf, nIOBufferSize, (int)USOCKETLib.tagSocketLevel.slSocket);<o:p>

                                                ClientSocket.SetSockOpt((int)USOCKETLib.tagSocketOption.soSndBuf, nIOBufferSize, (int)USOCKETLib.tagSocketLevel.slSocket);<o:p>


                                                ClientSocket.SetSockOptAtSvr((int)USOCKETLib.tagSocketOption.soRcvBuf, nIOBufferSize, (int)USOCKETLib.tagSocketLevel.slSocket);<o:p>

                                                ClientSocket.SetSockOptAtSvr((int)USOCKETLib.tagSocketOption.soSndBuf, nIOBufferSize, (int)USOCKETLib.tagSocketLevel.slSocket);<o:p>










                for (n = 0; n < m_aDBHandler.Count; n++)<o:p>


                        CDBHandler DBHandler = (CDBHandler)m_aDBHandler[n];<o:p>



                return (m_aDBHandler.Count == m_SocketPool.ConnectedSockets);<o:p>


      As the sample shows, you can batch a lot of requests and send all of them onto a remote server. We need a way to find the time when all of requests are processed and returned so that I can tell another application that the process is ended. Actually, you can do this easily using the following code.<o:p>

protected virtual void OnAllRequestProcessed(int hSocket, short sRequestID, int nLen, int nLenInBuffer, short sFlag)<o:p>


                if (sFlag != (short)USOCKETLib.tagReturnFlag.rfCompleted)<o:p>


                //this callback is called with a socket pool thread.<o:p>

                if (m_ClientSocket.CountOfRequestsInQueue == 1)<o:p>


                        //when the queue contains one (current) request only<o:p>

                        //we know that all of requests are already processed.<o:p>

                        if (m_cb != null)<o:p>


                                //invoke an EndEventHandler<o:p>



                                m_cb = null;<o:p>




      We use a pre-recorded callback (m_cb) to inform another application, for example, a web application that the process is ended. For simplifying code, the code also unlock a DB handler in the above. To lock a socket and its bound database objects, CDBHandler uses the following code to implement it simply.<o:p>

public static CDBHandler LockDBHandler(AsyncCallback cb, int nTimeOut)<o:p>


                if (cb == null)<o:p>

                        return null;<o:p>

                USocket ClientSocket = null;<o:p>



                        ClientSocket = m_SocketPool.LockASocket(nTimeOut, null);<o:p>


                catch (COMException err)<o:p>


                        string strErrorMessage = err.Message;<o:p>

                        int hr = err.ErrorCode;<o:p>

                        return null;<o:p>


                CDBHandler dbHandler = SeekDBHandler(ClientSocket.Socket);<o:p>

                if (dbHandler != null)<o:p>


                        dbHandler.m_cb = cb;<o:p>








                        dbHandler.m_DS = new DataSet();<o:p>


                return dbHandler;<o:p>


      SocketPro is very powerful and has a lot of features. As a sample, the code also has three delegates to monitor dataset generation when we fetch one or multiple rowsets. For all of other codes, you can see the source file, debug it and see code execution. After understanding how the code works, you can add more and more features (For example, monitoring various socket events and data movement, canceling fetching records, notifying messages, online compressing, securing data movement , sending requests when fetching records, …… etc) according to your requirements. <o:p>

6.   FAQs:<o:p>

      I listed a number of frequent asked questions about this article so that it further eliminates some your concerns.<o:p><o:p>

      Does the remote database service is free? Can I get source code for it?<o:p>

You can use udb.dll and uodbsvr.dll through SocketPro for free. Beginning with SocketPro version, UDAParts makes remote database service completely free to any one for any purpose as long as you do not do anything against or harmful to UDAParts. In regards to source file, you can see the source file for udb.dll inside SocketPro package. However, you can’t see the source file for uodbsvr.dll that is written from our OleDBPro library. Because our OleDBPro and its source code are not free to the public, we will not open its source code to the public but to our customers only.<o:p>

How fast and scalable with remote database service? Do you have any comparison with dotNet remoting in performance and scalability?<o:p>

We have compared our SocketPro with dotNet remoting as described in the article Develop high performance distributed applications with batching, asynchrony, and parallel computation -- Performance comparison between SocketPro and dotNet remoting. You can see how fast and scalable SocketPro is. In short, dotNet remoting can never match SocketPro in performance and scalability under any cases no matter how much time and effort you put on dotNet remoting. SocketPro is carefully written directly from window socket APIs using ATL/COM that makes sure it delivers super performance and scalability for all of development languages with special features, batching, asynchrony and parallel computation with online compressing, although it has COM interop cost between native code and managed code.

Can I lock two or more DB handlers one time from your sample code so that I can process multiple requests from one page in parallel instead of in queue as shown in this sample?<o:p>

Yes, you can lock two or more database handlers one time and divide all of requests onto different socket and database objects for processing in parallel. This sample is written for processing all requests in batch and also in queue. To process all of requests in parallel, you need to modify the source code after understanding how to know all of requests over different sockets are processed and returned. <o:p>

      As you may know that MS SQL server provides notification service. Can I use the sample code to notify other clients when I change a table? <o:p>

      Yes, you can! SocketPro has a built-in service for every socket connection. After a set of requests are processed and returned in the function void EndAsyncOperation(IAsyncResult ar), you can call the below code to notify all of clients that joined group 1.<o:p>

      m_DBHandler.Socket.Speak("All guys, I just updated the table Orders where OrderID = 10250. Please update your GUI controls with latest data!", 1);<o:p><o:p>

      For details, see the article Notify your coworkers any messages anywhere.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Yuancai (Charlie) Ye
Software Developer (Senior)
United States United States
Yuancai (Charlie) Ye, an experienced C/C++ software engineer, lives in Atlanta, Georgia. He is an expert at continuous inline request/result batching, real-time stream processing, asynchronous data transferring and parallel computation for the best communication throughput and latency. He has been working at SocketPro ( for more than fifteen years.

You may also be interested in...


Comments and Discussions

General[Message Deleted] Pin
it.ragester2-Apr-09 21:51
memberit.ragester2-Apr-09 21:51 
[Message Deleted]
GeneralGreat! Pin
leiyang1192027-May-06 9:46
memberleiyang1192027-May-06 9:46 
GeneralRe: Great! Pin
Yuancai (Charlie) Ye28-May-06 1:18
memberYuancai (Charlie) Ye28-May-06 1:18 
GeneralCorrect firefox problem Pin
Yuancai (Charlie) Ye25-May-06 17:39
memberYuancai (Charlie) Ye25-May-06 17:39 
GeneralNice work! Pin
mrmubi6-Dec-05 16:40
membermrmubi6-Dec-05 16:40 
GeneralRe: Nice work! Pin
Yuancai (Charlie) Ye7-Dec-05 1:59
memberYuancai (Charlie) Ye7-Dec-05 1:59 
Generalas Pin
Anonymous25-Oct-05 19:11
sussAnonymous25-Oct-05 19:11 
GeneralRe: as Pin
Anonymous25-Oct-05 19:11
sussAnonymous25-Oct-05 19:11 
GeneralRe: as Pin
Anonymous25-Oct-05 19:11
sussAnonymous25-Oct-05 19:11 
GeneralRe: as Pin
Anonymous25-Oct-05 19:12
sussAnonymous25-Oct-05 19:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170813.1 | Last Updated 25 May 2006
Article Copyright 2005 by Yuancai (Charlie) Ye
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid