forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleClient.java
More file actions
43 lines (39 loc) · 1.3 KB
/
SimpleClient.java
File metadata and controls
43 lines (39 loc) · 1.3 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
/**
* Java. Level 2. Lesson 6
* Simple chat client
*
* @author Sergey Iryupin
* @version 0.1 dated Jan 16, 2018
*/
import java.net.Socket;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Scanner;
class SimpleClient {
final String SERVER_ADDR = "127.0.0.1"; // or "localhost"
final int SERVER_PORT = 2048;
final String CLIENT_PROMPT = "$ ";
final String CONNECT_TO_SERVER = "Connection to server established.";
final String CONNECT_CLOSED = "Connection closed.";
final String EXIT_COMMAND = "exit"; // command for exit
public static void main(String[] args) {
new SimpleClient();
}
SimpleClient() {
String message;
try (Socket socket = new Socket(SERVER_ADDR, SERVER_PORT);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
Scanner scanner = new Scanner(System.in)) {
System.out.println(CONNECT_TO_SERVER);
do {
System.out.print(CLIENT_PROMPT);
message = scanner.nextLine();
writer.println(message);
writer.flush();
} while (!message.equals(EXIT_COMMAND));
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
System.out.println(CONNECT_CLOSED);
}
}