Last active
April 22, 2016 01:47
-
-
Save kylelk/a55ed824cc5739f060509e3b5169ba05 to your computer and use it in GitHub Desktop.
How to connect to a Redis server using Ada
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with GNAT.Sockets; | |
with Ada.Text_IO; | |
with Ada.Strings.Unbounded; | |
with Ada.Streams; use Ada.Streams; | |
procedure Redis_Client is | |
package TIO renames Ada.Text_IO; | |
package UBS renames Ada.Strings.Unbounded; | |
Host : constant String := "127.0.0.1"; | |
Port_Number : GNAT.Sockets.Port_Type := 6379; | |
Host_Entry : GNAT.Sockets.Host_Entry_Type := | |
GNAT.Sockets.Get_Host_By_Name (Host); | |
Address : GNAT.Sockets.Sock_Addr_Type; | |
Socket : GNAT.Sockets.Socket_Type; | |
function Redis_Call | |
(Conn : in out GNAT.Sockets.Socket_Type; | |
Cmd : String) return String | |
is | |
Channel : GNAT.Sockets.Stream_Access; | |
Data : Ada.Streams.Stream_Element_Array (1 .. 1024); | |
Size : Ada.Streams.Stream_Element_Offset; | |
Ret : Ada.Strings.Unbounded.Unbounded_String; | |
CRLF : constant String := ASCII.CR & ASCII.LF; | |
use Ada.Strings.Unbounded; | |
begin | |
Channel := GNAT.Sockets.Stream (Conn); | |
String'Write (Channel, Cmd & CRLF); | |
loop | |
GNAT.Sockets.Receive_Socket (Conn, Data, Size); | |
for I in 1 .. Size loop | |
Ret := Ret & Character'Val (Data (I)); | |
end loop; | |
if Size < Data'Length then | |
exit; | |
end if; | |
end loop; | |
return UBS.To_String (Ret); | |
end Redis_Call; | |
begin | |
-- Open a socket connection | |
Address.Addr := GNAT.Sockets.Addresses (Host_Entry, 1); | |
Address.Port := Port_Number; | |
GNAT.Sockets.Create_Socket (Socket); | |
GNAT.Sockets.Connect_Socket (Socket, Address); | |
-- send call to redis server and read result | |
TIO.Put_Line(Redis_Call(Socket, "PING")); | |
GNAT.Sockets.Close_Socket (Socket); | |
end Redis_Client; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment