WinForm implementation of RABBITMQ official website 6 cases-RPC

Source: Internet
Author: User
Tags rabbitmq

Client code:

namespacerabbitmqdemo{ Public Partial classRpc:form {Private ReadOnly StaticRPC _rpc; Action<string, textbox>SetText; StaticRPC () {_rpc=NewRPC (); }        /// <summary>        ///single-case mode/// </summary>         Public StaticRPC Singleform {Get{return_rpc;} }        PrivateRPC () {checkforillegalcrossthreadcalls=false;        InitializeComponent (); }        Private voidBtnsendmsg_click (Objectsender, EventArgs e) {//RPC Client makes a request            stringMessage =Txtpublisher.text; if(Message. Trim (). Length <=0) {MessageBox.Show ("Please enter a message to send"); } rpcclient Client=Newrpcclient (); varResponse =client.            Call (message); Txtrpcclient.text+=string. Format ("{0}\r\n", response); Client.        Close (); }        /// <summary>        ///Client Class/// </summary>        Private classrpcclient {#regionParameters/// <summary>            ///RABBITMQ Connection/// </summary>            Private ReadOnlyiconnection Connection; /// <summary>            ///Channel/// </summary>            Private ReadOnlyIModel Channel; /// <summary>            ///queue associated with the client/// </summary>            Private ReadOnly stringReplyqueuename; /// <summary>            ///Consumer/// </summary>            Private ReadOnlyEventingbasicconsumer Consumer; //private readonly blockingcollection<string> resqueue = new blockingcollection<string> ();            Private ReadOnlyblockingcollection<string> resqueue =Newblockingcollection<string>(); /// <summary>            ///Message Properties/// </summary>            Private ReadOnlyibasicproperties props; #endregion            /// <summary>            ///constructor Function/// </summary>             Publicrpcclient () {varFactory =NewConnectionFactory () {HostName ="localhost" }; Connection=Factory.                CreateConnection (); Channel=connection.                Createmodel (); Replyqueuename=Channel. Queuedeclare ().                QueueName; Consumer=NewEventingbasicconsumer (channel); Props=Channel.                Createbasicproperties (); //associated Response,request and Replyqueuename                varCorrelationid =Guid.NewGuid ().                ToString (); Props. Correlationid=Correlationid; Props. ReplyTo=Replyqueuename; Consumer. Received+ = (model, ea) = =                  {                      varResponse =Encoding.UTF8.GetString (ea.                      Body); //determines that the response returned is from this request                      if(EA.) Basicproperties.correlationid = =Correlationid) Resqueue.add (response);            }; }             Public stringCall (stringmsg) {                varMsgbytes =Encoding.UTF8.GetBytes (msg); Channel. Basicpublish (Exchange:"", Routingkey:"Rpc_queue", Basicproperties:props, body:msgbytes); Channel. Basicconsume (Consumer:consumer, Queue:replyqueuename, Noack: /c3>true); returnResqueue.take (); }             Public voidClose () {connection.            Close (); }        }//class    }}
View Code

Service-Side code:

namespacerpcserver{ Public Partial classRpcserver:form {Private ReadOnly StaticRpcserver _rpcserver; Action<string, textbox>SetText; StaticRpcserver () {_rpcserver=NewRpcserver (); }        /// <summary>        ///single-case mode/// </summary>         Public StaticRpcserver Singleform {Get{return_rpcserver;} }        PrivateRpcserver () {checkforillegalcrossthreadcalls=false;            InitializeComponent (); Receivemsg (txtrpcserver);//Service SideSetText + =Onsettext; }        /// <summary>        ///receiving messages from the service side/// </summary>        Private voidreceivemsg (TextBox box) {Try            {                varFactory =NewConnectionFactory () {HostName ="localhost" }; varConnection =Factory.                CreateConnection (); varChannel =connection.                Createmodel (); //declaring queuesChannel. Queuedeclare (Queue:"Rpc_queue", Durable:false, Exclusive:false, Autodelete:false, arguments:NULL); //each consumer consumes at most one message, and no messages are received until the message is confirmed.Channel. Basicqos (0,1,false); varConsumer =NewEventingbasicconsumer (channel); Consumer. Received+ = (model, ea) = =                {                    stringResponse =NULL; varBODY =ea.                    Body; varProps =ea.                    Basicproperties; varReplyprops =Channel.                    Createbasicproperties (); Replyprops.correlationid=props.                    Correlationid; varmsg =Encoding.UTF8.GetString (body); //Service side Display contentbox.                    Invoke (SetText, MSG, box); Response="I will reply to you: I have received the message-"+msg; varResponseBytes =Encoding.UTF8.GetBytes (response); Channel. Basicpublish (Exchange:"", Routingkey:props.                    ReplyTo, Basicproperties:replyprops, body:responsebytes); //Send Message confirmation to RABBITMQ manuallyChannel. Basicack (Deliverytag:ea. Deliverytag, multiple:false);                }; Channel. Basicconsume (Queue:"Rpc_queue", Noack:false,//Manual Confirmation MessageConsumer:consumer); }            Catch(Exception ex) {MessageBox.Show (ex).            ToString ()); }        }        Private voidOnsettext (stringtext, TextBox box) {box. Text+=string. Format ("{0}\r\n", text); }    }}
View Code

Interface:

Approximate process:

Client impersonation sends a request to the queue, the server consumes the message from the queue and simulates sending a response to the queue, the client consumes the message (new 2 WinForm program test, one client, one server)

VS launch Two WinForm programs simultaneously: mouse Click Solution-Right Button Properties-Multiple Startup items-action changed to start-OK-ready

Test results:

WinForm implementation of RABBITMQ official website 6 cases-RPC

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.