forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloServer.java
More file actions
39 lines (35 loc) · 1.19 KB
/
HelloServer.java
File metadata and controls
39 lines (35 loc) · 1.19 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
/**
* Java. Level 2. Lesson 6. Networking
* Class HelloServer: waiting and sending message to the client
*
* @author Sergey Iryupin
* @version dated Jan 12, 2018
*/
import java.net.*;
import java.io.*;
class HelloServer {
public static void main(String[] args) {
new HelloServer();
}
HelloServer() {
try (ServerSocket server = new ServerSocket(1024)) {
String ipAddress = getPublicIP("http://checkip.amazonaws.com");
System.out.println("Server started on IP " + ipAddress);
while (true) {
Socket socket = server.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println("Server from IP " + ipAddress + " says: Hello");
System.out.println("Message sent to client.");
writer.close();
}
} catch (IOException ex) {
System.out.println(ex);
}
}
private String getPublicIP(String url) throws IOException {
URL checkURL = new URL(url);
BufferedReader reader = new BufferedReader(
new InputStreamReader(checkURL.openStream()));
return reader.readLine();
}
}