Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.Arrays;
- import java.util.List;
- public class Client {
- private final String HOST;
- private final int PORT;
- public Client(String host, int port){
- this.HOST = host;
- this.PORT = port;
- }
- // will overwrite any existing values for a given key
- public String putKeyValue(String key, String value){
- return send(String.format("Add:%s-%s", key, value));
- }
- // will append values to any existing key
- public String putKeyValueList(String key, String...values){
- return send(String.format("AddList:%s-%s", key, String.join(",", values)));
- }
- // key must point to a single value
- public String getValue(String key){
- return send(String.format("Get:%s", key));
- }
- // key must point to a list
- public List<String> getValues(String key){
- return Arrays.asList(send(String.format("GetList:%s", key)).split(","));
- }
- public void shutdown(){
- send("shutdown:true");
- }
- private String send(String msg){
- try(Socket client = new Socket(HOST, PORT);
- PrintWriter output = new PrintWriter(client.getOutputStream(), true);
- BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
- //send msg
- output.println(msg);
- // return response
- return input.readLine();
- }catch (IOException e){
- e.printStackTrace();
- return "Error";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement