-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
70 lines (63 loc) · 1.82 KB
/
Client.java
File metadata and controls
70 lines (63 loc) · 1.82 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private Socket socket;
BufferedReader in;
PrintWriter out;
ClientFrame frame;
public Client(String serverName, int serverPort) {
try {
socket = new Socket(serverName, serverPort);
this.frame = new ClientFrame(socket);
System.out.println("Connected: " + socket);
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new PrintWriter(socket.getOutputStream(), true);
new Thread(new Runnable() {
public void run() {
try {
startReading();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}catch(Exception e) {
e.printStackTrace();
System.err.println("Exception.");
}
}
private void startReading() throws IOException {
String text = "";
while(this.socket != null && this.socket.isConnected() && !text.equals("null")) {
try{
text = in.readLine();
this.frame.add(text);
}catch(Exception e){
System.err.println("Socket Exception in read stream");
e.printStackTrace();
}
}
System.err.println("client disconnected.");
}
private void sendMsg(String msg) {
if(this.socket.isConnected()) {
try {
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
out.println(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("Cant send msg");
}
}
}