Use thrift to implement the sample code for js and C # Communication

Source: Internet
Author: User

1. Why use thrift js C #?

1.1 first, js accesses C # through thrift, which is actually a c/s mode. Thrift is a communication tool, js is a client, and C # is a server.

1.2 use js to directly communicate with thrift server. Makes web development easier. If you use Web Service, you need to implement serialization and deserialization at both ends of the C/S, and you also need to handle exceptions on your own, reducing development efficiency. Thrift automatically generates operation classes at both ends. You only need to process the internal logic of the method.

1.3 js directly communicates with thrift server, which can improve the performance and use C # To develop the server. The development efficiency is also very high. (Those web services are weak)

1.4 of course, we cannot only see advantages. This method also has obvious disadvantages: If web service is used, web pages and web services can be encapsulated in a project. After being deployed to IIS, web services can exist in a website. After thrift is used, you need to manually manage thrift programs. Including:

1.4.1 you need to have the absolute control right of the server. For example, you can directly log on to the operating system of the server for operations. Therefore, this method is not suitable if you only have one webpage space. Of course, you can also bind thrift in the web service, but you need to manually perform serialization and deserialization operations, and the two conversions lower the performance, against the original intention

1.4.2 Add Automatic startup and monitoring programs to the thrift server program to automatically restart thrift after it crashes.

2. Environment

Win7-VS2012-. net 4.0 C # console Project (used to host thrift)

Win7-VS2012-. net 4.0 C # Web project (for debugging js, super convenient)

3. Steps (the following steps are difficult for Tom. QQ group: 23152359)

3.1 go to thrift to download the thrift library, which is 0.9.0 currently.

3.2 go to thrift to download the compiled thrift compiler under win, which is an exe file.

3.3 write a data structure definition file. I only use the service here, and no custom data structure is defined.

Data.txt:

Copy codeThe Code is as follows: service UserStorage
{
I32 Sum (1: i32 arg_number1, 2: i32 arg_number2 ),
String GetString ()
}

3.4 use the thrift compiler to compile it on the command line:
Run. bat:Copy codeThe Code is as follows: thrift-0.9.0.exe -- gen csharp data.txt
Thrift-0.9.0.exe -- gen js data.txt
Pause

3.5 create a C # console project named CSharpServer. net 4.0.

3.6 add an existing project for this project: thrift library directory \ thrift-0.9.0 \ lib \ csharp \ src \ Thrift. csproj, and then reference this project.

3.7 compile the UserStorage compiled by thrift. cs (in the gen-csharp directory), drag to the root directory of the CSharpServer project in solution manager, UserStorage. cs and Program. cs should be at the same level.

3.8 create a UserStorage processing class UserStorageHandle. cs in the CSharpServer project: (it should be at the same level as UserStorage. cs and Program. cs)

Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace CSharpServer
{
Public class UserStorageHandle: UserStorage. Iface
{

Public UserStorageHandle ()
{

}

Public int Sum (int arg_number1, int arg_number2)
{
Int result = arg_number1 + arg_number2;
Console. writeLine (DateTime. now. toString () + "received request: Sum, parameter: arg_number1 =" + arg_number1.ToString () + ", arg_number2 =" + arg_number2.ToString () + ", return: result =" + result. toString ());
Return result;
}

Private static int Counter = 0;

Public string GetString ()
{
Int currentCounter = System. Threading. Interlocked. Increment (ref UserStorageHandle. Counter );
Console. writeLine (DateTime. now. toString () + "received request: GetString, parameter: None, return: result = \" thrift is OK: "+ currentCounter. toString () + "\"");
Return "thrift is OK:" + currentCounter. ToString ();
}

}
}

3.9 Main Program. cs:

Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using Thrift. Transport;
Using Thrift. Protocol;
Using Thrift. Server;
Using System. Net;

Namespace CSharpServer
{
Class Program
{
Private static HttpListener httpListener = null;
Private static THttpHandler httpServer = null;

Static void Main (string [] args)
{
String serviceUrl = "http: // localhost: 99 /";
Try
{
UserStorageHandle handle = new UserStorageHandle ();
UserStorage. Processor processor = new UserStorage. Processor (handle );
TProtocolFactory protocolFactory = new TJSONProtocol. Factory ();

Program. httpServer = new THttpHandler (processor, protocolFactory );

Program. httpListener = new HttpListener ();
Program. httpListener. Prefixes. Add (serviceUrl );
Program. httpListener. Start ();
IAsyncResult result = Program. httpListener. BeginGetContext (new AsyncCallback (WebRequestCallback), null );
Console. WriteLine ("Thrift service started successfully, URL is" + serviceUrl );
}
Catch (System. Exception ex)
{
Console. WriteLine ("error:" + ex. Message );
Console. WriteLine ("press enter to exit ");
Console. ReadLine ();
Return;
}
Console. WriteLine ("to end the program, close the window directly or press Enter. ");
Console. ReadLine ();
}

Public static void WebRequestCallback (IAsyncResult result)
{
If (Program. httpListener = null)
{
Console. WriteLine ("error occurred: HttpListener has been disabled ");
Console. WriteLine ("press enter to exit ");
Console. ReadLine ();
Return;
}

HttpListenerContext httpListenerContext = Program. httpListener. EndGetContext (result );

Program. httpListener. BeginGetContext (new AsyncCallback (WebRequestCallback), null );

Program. httpServer. ProcessRequest (httpListenerContext );
}

}
}

3.10 press F5 to start the CSharpServer project.

3.11 create a new VS2012 Project (buy it out of memory) and create a C #. net 4.0 Web empty project called JsProject.

3.12 go to jquery official website download jquery-1.9.1.js (mini version is also OK, casually)

3.13 compile the thrift js file data_types.js and UserStorage. js, thrift library js library file (thrift library directory \ thrift-0.9.0 \ lib \ js \ thrift. js), and the just downloaded jq file jquery-1.9.1.js, all dragged to Solution Explorer's JsProject project root directory:

Data_types.js \ jquery-1.9.1.js \ thrift. js \ UserStorage. js should be at the same level as Web. config.

3.14 create a test.html file under the root directory. test.html should be at the same level as Web. config:

Test.html:

Copy codeThe Code is as follows: <! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> </title>
<Script type = "text/javascript" src = "jquery-1.9.1.js"> </script>
<Script type = "text/javascript" src = "data_types.js"> </script>
<Script type = "text/javascript" src = "thrift. js"> </script>
<Script type = "text/javascript" src = "UserStorage. js"> </script>

<Script>
$ (Document). ready (function ()
{
Var debugPosation = 0;
Try
{
Var transport = new Thrift. Transport ("http://www.jb51.net /");
Var protocol = new Thrift. Protocol (transport );
Var client = new UserStorageClient (protocol );

Var result_GetString = client. GetString ();
Var result_Sum = client. Sum (255,322 );
}
Catch (e)
{
Alert ("error bird:" + e. message );
}
});
</Script>
</Head>
<Body>
</Body>
</Html>

3.15 "var debugPosation = 0;" for test.html, click the breakpoint, and then F5 to see the effect.

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.