-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.java
74 lines (63 loc) · 1.86 KB
/
Client.java
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
import java.net.Socket;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
private boolean running;
public Client() {
running = true;
}
public void connectTo(String ip, int port) throws IOException {
connectToServer(ip, port);
startTerminalInputThread();
printReceivedMessages();
}
private void connectToServer(String ip, int port) throws IOException{
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
private void startTerminalInputThread() {
TerminalInput terminalInput = new TerminalInput(this);
new Thread(terminalInput).start();
}
private void printReceivedMessages() throws IOException {
String message;
while(running && (message = receiveMessage()) != null) {
System.out.println(message);
}
disconnect();
}
private String receiveMessage() throws IOException {
return in.readLine();
}
public boolean isRunning() {
return running;
}
public void stopRunning() {
running = false;
}
public void sendMessage(String message) throws IOException{
out.println(message);
}
public void disconnect() {
running = false;
try {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
if(clientSocket != null) {
clientSocket.close();
}
} catch(Exception e) {
System.out.println("Error occured disconnecting: " + e);
}
}
}