Advertisement
Guest User

Untitled

a guest
Feb 15th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.Socket;
  6. import java.util.Arrays;
  7. import java.util.List;
  8.  
  9. public class Client {
  10.  
  11.     private final String HOST;
  12.     private final int PORT;
  13.  
  14.     public Client(String host, int port){
  15.         this.HOST = host;
  16.         this.PORT = port;
  17.     }
  18.  
  19.     // will overwrite any existing values for a given key
  20.     public String putKeyValue(String key, String value){
  21.         return send(String.format("Add:%s-%s", key, value));
  22.     }
  23.  
  24.     // will append values to any existing key
  25.     public String putKeyValueList(String key, String...values){
  26.         return send(String.format("AddList:%s-%s", key, String.join(",", values)));
  27.     }
  28.  
  29.     // key must point to a single value
  30.     public String getValue(String key){
  31.         return send(String.format("Get:%s", key));
  32.     }
  33.  
  34.     // key must point to a list
  35.     public List<String> getValues(String key){
  36.         return Arrays.asList(send(String.format("GetList:%s", key)).split(","));
  37.     }
  38.  
  39.     public void shutdown(){
  40.         send("shutdown:true");
  41.     }
  42.  
  43.     private String send(String msg){
  44.         try(Socket client = new Socket(HOST, PORT);
  45.             PrintWriter output = new PrintWriter(client.getOutputStream(), true);
  46.             BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
  47.  
  48.             //send msg
  49.             output.println(msg);
  50.  
  51.             // return response
  52.             return input.readLine();
  53.         }catch (IOException e){
  54.             e.printStackTrace();
  55.             return "Error";
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement