The general form of the Redis request protocol:
*< number of parameters > cr lf$1 bytes > cr LF1 data > cr lf...$< number of bytes of parameter N >< c5> CR LF< parameter N data > CR LF
Note: CR is indicated as \ r; LF means \ n
Here is an example:
*3$3set$5mykey$7myvalue
Redis reply
The Redis command returns several different types of replies.
By checking the first byte of the data sent back by the server, you can determine what type of reply this is:
- The first byte of State reply (status reply) is
"+"
- The first byte of the error reply (Reply) is
"-"
- The first byte of an integer reply (integer reply) is
":"
- The first byte of a bulk reply (bulk reply) is
"$"
- The first byte of a multiple bulk reply (multi bulk Reply) is
"*"
Implementation code (C #)
1. Connect Redis via Socket:
// connect to Redis via socket New Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); S.connect (" 127.0.0.1"6379);
2. Send Instructions
stringKey ="setkeytest";//Set the keystringValue ="Set the value";//Set the valueStringBuilder Sbsend =NewStringBuilder (); Sbsend.append ("*3\r\n");//Number of parameters 3stringcmd ="SET"; Sbsend.append ("$"+ Encoding.UTF8.GetBytes (cmd). Length +"\ r \ n");//length of parameter 1Sbsend.append (cmd +"\ r \ n");//parameter 1 (set Directive)Sbsend.append ("$"+ Encoding.UTF8.GetBytes (key). Length +"\ r \ n");//length of parameter 2Sbsend.append (""+ key +"\ r \ n");//parameter 2 (Value of Set)Sbsend.append ("$"+ Encoding.UTF8.GetBytes (value). Length +"\ r \ n");//length of Parameter 3Sbsend.append (""+ Value +"\ r \ n");//Parameter 3 (Value of Set)Console.WriteLine ("the command sent:"); Console.Write (Sbsend.tostring ());byte[] data = Encoding.UTF8.GetBytes (sbsend.tostring ());//convert the request to a byte array
3, receive the reply
byte[] result =New byte[1024x768];intResultlength = s.receive (result);//receive replies//Reassemble a result based on the length of data receivedbyte[] Newresult =New byte[resultlength]; for(inti =0; i < resultlength; i++) {Newresult[i]=result[i];}stringstrresult = Encoding.UTF8.GetString (Newresult);//Convert the result to stringConsole.Write (strresult); Console.Write (Strresult.trim ()=="+ok"?"Setup succeeded! ":"Setup failed!");//determine if the setting is successful
Execution effect
Write your own Redis client (C # implementation) 2-set request and Status reply (set)