88import org .slf4j .Logger ;
99import org .slf4j .LoggerFactory ;
1010
11+ import java .net .URISyntaxException ;
12+ import java .net .http .HttpClient ;
13+ import java .net .http .HttpRequest ;
14+ import java .net .http .HttpResponse ;
15+ import java .time .Duration ;
16+
1117public class PingRemote implements ModInitializer {
12- public static final String MOD_ID = "pingremote" ;
13- public static final Logger LOGGER = LoggerFactory .getLogger (MOD_ID );
14- public static PingRemoteConfig config ;
15- public static int counter ;
16-
17- @ Override
18- public void onInitialize () {
19- LOGGER .info ("Ping Remote initialized." );
20- config = ConfigBuilder .load (PingRemoteConfig .class , MOD_ID );
21-
22- ServerTickEvents .START_SERVER_TICK .register ((serverWorld ) -> {
23- PingRemote .counter ++;
24- });
25-
26- ServerTickEvents .END_WORLD_TICK .register ((serverWorld ) -> {
27- if (PingRemote .counter == PingRemote .config .getTickAmount ()) {
28-
29- }
30- });
31- }
18+ public static final String MOD_ID = "pingremote" ;
19+ public static final Logger LOGGER = LoggerFactory .getLogger (MOD_ID );
20+ public static PingRemoteConfig config ;
21+ public static int counter ;
22+
23+ @ Override
24+ public void onInitialize () {
25+ LOGGER .info ("Ping Remote initialized." );
26+ config = ConfigBuilder .load (PingRemoteConfig .class , MOD_ID );
27+
28+ ServerTickEvents .START_SERVER_TICK .register ((serverWorld ) -> {
29+ PingRemote .counter ++;
30+ });
31+
32+ ServerTickEvents .END_WORLD_TICK .register ((serverWorld ) -> {
33+ if (counter == config .getTickAmount ()) {
34+ counter = 0 ;
35+
36+ try (HttpClient client = HttpClient .newBuilder ()
37+ .version (HttpClient .Version .HTTP_2 )
38+ .connectTimeout (Duration .ofSeconds (10 ))
39+ .build ()) {
40+
41+ try {
42+ HttpRequest request = HttpRequest .newBuilder ()
43+ .uri (config .getRemoteHost ().toURI ())
44+ .timeout (Duration .ofMinutes (1 ))
45+ .build ();
46+
47+ client .sendAsync (request , HttpResponse .BodyHandlers .ofString ())
48+ .thenApply (HttpResponse ::body )
49+ .thenAccept (System .out ::println );
50+ } catch (URISyntaxException e ) {
51+ LOGGER .warn ("Cannot ping remote host" );
52+ }
53+ }
54+ }
55+ });
56+ }
3257}
0 commit comments