Write Redis client by yourself (C # implementation) 3,

Source: Internet
Author: User

Write Redis client by yourself (C # implementation) 3,
Implementation Code (C #) 1. Send the GET command

String keyGet = "SetKeyTest"; // The key StringBuilder sbSendGet = new StringBuilder (); sbSendGet. append ("* 2 \ r \ n"); // number of parameters 3 string character GET = "GET"; sbSendGet. append ("$" + Encoding. UTF8.GetBytes (batch get ). length + "\ r \ n"); // The Length of parameter 1 sbSendGet. append (writable GET + "\ r \ n"); // parameter 1 (GET command) sbSendGet. append ("$" + Encoding. UTF8.GetBytes (keyGet ). length + "\ r \ n"); // The Length of parameter 2 sbSendGet. append ("" + keyGet + "\ r \ n"); // parameter 2 (get key) Console. writeLine ("sent command:"); Console. write (sbSendGet. toString (); byte [] bytes ET = Encoding. UTF8.GetBytes (sbSendGet. toString (); // converts a request to a byte array s. send (dataGet); // Send command
2. Receive batch replies
Byte [] resultGET = new byte [512]; int resultGetLength = s. receive (resultGET); // receives a response // reassemble a result byte [] newResultGet = new byte [resultGetLength] based on the received data length; for (int I = 0; I <resultGetLength; I ++) {newResultGet [I] = resultGET [I];} string strGetResult = Encoding. UTF8.GetString (newResultGet); // convert the result to stringConsole. write ("obtained value:" + strGetResult );
3. Results:

/// <Summary> /// send command // </summary> /// <param name = "client"> </param> /// <param name = "datas"> </param> // <returns> </returns> public static string SendCmd (this Socket client, params byte [] [] datas) {client. send (Encoding. UTF8.GetBytes ("*" + datas. length + "\ r \ n"); for (int I = 0; I <datas. length; I ++) {client. send (Encoding. UTF8.GetBytes ("$" + datas [I]. length); client. send (Encoding. UTF8.GetBytes ("\ r \ n"); client. send (datas [I]); client. send (Encoding. UTF8.GetBytes ("\ r \ n");} return Reply (client );}2. receive replies

/// <Summary> /// receive the reply /// </summary> /// <param name = "client"> </param> /// <returns> </returns> public static string Reply (Socket client) {BufferedStream s = new BufferedStream (new NetworkStream (client); int B = s. readByte (); // read the first byte string result; switch (B) {// the first byte of status reply (status reply) is "+" case '+ ': result = ReadLine (s); return "+" + result; // the first byte of error reply is "-" case '-': result = Read Line (s); throw new Exception (result); // throw an Exception // the first byte of integer reply is ":" case ':': result = ReadLine (s); return ":" + result; // the first byte of bulk reply is "$" case '$ ': result = ReadLine (s); // read the number of data bytes first. writeLine ("$" + result); int count = int. parse (result); // if the requested value does not exist, the special value-1 is used as the reply length value for batch reply. if (count =-1) {return null;} result = ReadByLength (s, count); Console. writeLine (resul T); return result; // the first byte of multi bulk reply is "*" case '*': result = ReadLine (s ); // read the number of data rows first. writeLine ("*" + result); int rows = int. parse (result); StringBuilder sb = new StringBuilder (); for (int I = 0; I <rows; I ++) {result = ReadLine (s); sb. appendLine (result); result = ReadLine (s); sb. appendLine (result);} Console. writeLine (sb); return sb. toString (); default: break;} return" ";} /// <Summary> /// read by length /// </summary> /// <param name = "s"> </param> /// <param name = "l"> </param> // <returns> </returns> public static string ReadByLength (BufferedStream s, long l) {byte [] bytes = new byte [l]; var r = s. read (bytes, 0, (int) l); return Encoding. UTF8.GetString (bytes );} /// <summary> /// read by row /// </summary> /// <param name = "s"> </param> /// <returns> </returns> public static string ReadLine (Buffer EdStream s) {StringBuilder sb = new StringBuilder (); int B = 0; while (B = s. ReadByte ())! =-1) {if (B = '\ R') {if (B = s. ReadByte ())! =-1) {if (B = '\ n') {break;} else {sb. append ('\ R') ;}} else {break ;}} sb. append (char) B);} return sb. toString ();}
3. GET and SET commands
Public static bool Set (this Socket client, string key, string value) {return Set (client, key, Encoding. UTF8.GetBytes (value);} public static bool Set (this Socket client, string key, byte [] value) {string result = SendCmd (client, Encoding. UTF8.GetBytes ("SET"), Encoding. UTF8.GetBytes (key), value); Console. writeLine (result); return result = "+ OK"; // If + OK, the setting is successful! // String} public static string Get (this Socket client, string key) {return SendCmd (client, Encoding. UTF8.GetBytes ("GET"), Encoding. UTF8.GetBytes (key); // string}
4. Restructured code

 

# Region SETstring key = "SetKeyTest"; // set the keystring value = "Set value"; // set the value var result = s. set (key, value); Console. writeLine (result? "Set successfully! ":" Setting failed! "); // Determine whether the setting is successful # endregion # region sending command Getstring keyGet =" SetKeyTest "; // The key var resultGet = s. get (keyGet); // send command Console. write ("obtained value:" + resultGet); # endregion

Is it concise ???

5. Results

 

Related Article

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.