Implementation of WCF Extensions ZEROMQ binding and Protocolbuffer message encoding (ii) Implementation IRequestChannel (2016-03-15 12:35)

Source: Internet
Author: User

Starting today, step-by-step describes how I implement custom ZEROMQ bindings and Protocolbuffer message encoding.

The ideas in this series come mainly from the Jing Jinnan Artech Series Blog-WCF follow-up tour, and the WCF Extension series blog from the WCF development team members Carlosfigueira.

The first thing to be clear is that the implementation of the communication and coding is separate. This is how WCF is designed. A custom binding contains a collection of bindingelementcollection, which can add multiple elementbinding. But there are two elementbinding essential, TransportBindingElement, messageencodingbindingelement. And ZEROMQ just provides communication technology, does not involve the specific encoding, its transmission data is a specified length of the string, as to how the string encoding, ZEROMQ is not known. This makes it possible to implement ZEROMQ as a transportbindingelement in the custom binding of WCF. Let's consider the transmission first, regardless of the coding.

The channel stack for WCF has been described in detail in the above two series of blogs, and I don't want to repeat it, just to talk about how I'm connecting WCF with ZEROMQ.

Implement IRequestChannel

New type Zmqrequestchannel, inherited from Channelbase,channelbase, is the channel base class provided by WCF.

The first step is to create a ZEROMQ socket, type req.

 This . Zmqcontext.createsocket (sockettype.req); socket. Connect (zmqaddress);

Ways to implement IRequestChannel

 Public Message Request (Message message, TimeSpan timeout)

Request is responsible for sending requests, blocking the current thread until a reply from the server is received. When sending a request, convert the message to byte[] and send it to ZEROMQ

            arraysegment<byte, BufferManager);                            Socket. Send (Requestdata.array);

The way of conversion is obtained through the Encoder object, encoder is created by Messageencodingbindingelement. The messageencodingbindingelement is part of the WCF channel stack, but the message does not pass through each channel, and messageencodingbindingelement is such a channel. It is only used by TransportBindingElement, when Transportchannel needs to encode and decode, TransportBindingElement's encoder will stand up to perform its duties.

When receiving a reply from the server, this is done:

            byte [] Replydata = Buffermanager.takebuffer (+);             int replaysize = socket. Receive (replydata);                             = Encoder. Readmessage (                new arraysegment<byte0, replaysize), BufferManager );            Buffermanager.returnbuffer (replydata);

Here, BufferManager is used to provide a receive cache, and the cache size is temporarily set to 1000. The purpose of using the cache is to be more efficient at allocation. When the reception is complete, remember to recycle.

IRequestChannel also needs to implement asynchronous send methods

        Object State );        Object State );          Message EndRequest (IAsyncResult result);

Refer to the synchronization method just now, send is divided into encoding, sending. Where the encoding is done locally, does not time out, and is sent due to dependency on the network environment and server state, this part needs to be moved to the asynchronous process.

Because the Send Async method is also used in Replychannel, I created the Zmqchannelbase base class, which derives from the Channelbase,zmqrequestchannel inherited from the new Zmqchannelbase base class. Put the asynchronous send method in the Zmqchannelbase.

 public  IAsyncResult beginrequest (Message message, AsyncCallback callback , object   State "{ return  base . Beginsendmessage (message, this  
        PublicObject State )        {            base. Throwifdisposedornotopen ();            ArraySegment<byte, BufferManager);             return  This . Beginwritedata (RequestData, timeout, callback, state);        }
The Beginwritedata method returns an AsyncResult object that implements the asynchronous interface IAsyncResult
        classSocketsendasyncresult:asyncresult {zmqchannelbase channel; ArraySegment<byte>buffer;  PublicSocketsendasyncresult (arraysegment<byte> buffer, Zmqchannelbase Channel, AsyncCallback callback,ObjectState ):Base(callback, state) { This. Channel =Channel;  This. Buffer =buffer;  This.            Startsending (); }            voidstartsending () {Socketsendhandle handler=NewSocketsendhandle (Delegate(Zmqsocket socket,byte[] data) {socket.                    Send (data);                Servicehanleddone.set ();                }); IAsyncResult Sendresult= handler. BeginInvoke (channel.socket, buffer. Array, OnSend,NULL); }            Static voidonsend (IAsyncResult result) {if(result.completedsynchronously) {return; } socketsendasyncresult thisptr=(Socketsendasyncresult) result.                asyncstate; Exception completionexception=NULL; BOOLShouldcomplete =false; if(shouldcomplete) {Thisptr.complete (false, completionexception); }            }             Public Static voidEnd (IAsyncResult result) {Asyncresult.end<SocketSendAsyncResult>(result); }        }

At this point, Requestchannel is complete, compared to Replychannel,requestchannel is relatively simple. The next article introduces Replychannel.

Implementation of WCF Extensions ZEROMQ binding and Protocolbuffer message encoding (ii) Implementation IRequestChannel (2016-03-15 12:35)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.