-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJavaClient.java
More file actions
80 lines (72 loc) · 2.79 KB
/
Copy pathJavaClient.java
File metadata and controls
80 lines (72 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class JavaClient {
private String serverUrl;
private HttpClient client;
public JavaClient(String serverUrl, int port) {
this.serverUrl = "localhost".equals(serverUrl) ? "http://127.0.0.1:" + port : serverUrl;
this.client = HttpClient.newHttpClient();
}
public void push(String key, String value) {
try {
String message = key + "," + value;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(serverUrl + "/push"))
.POST(BodyPublishers.ofString(message))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println("Received from server: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
public void pull() {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(serverUrl + "/pull"))
.GET()
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println("Received from server: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
private void subscribeRunner(String url, Consumer<String> f) {
Executors.newSingleThreadExecutor().submit(() -> {
while (true) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url + "/pull"))
.GET()
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String data = response.body();
if (!"no message".equals(data)) {
f.accept(data);
} else {
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void subscribe(Consumer<String> f) {
subscribeRunner(serverUrl, f);
}
public static void main(String[] args) {
JavaClient client = new JavaClient("localhost", 8000);
client.subscribe(data -> System.out.println("Received data: " + data));
// Example usage
client.push("key", "value");
client.push("key", "value2");
}
}