-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicClient.java
73 lines (60 loc) · 2.27 KB
/
BasicClient.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
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* @author alyacarina
*/
public class BasicClient {
private static final String CONNECTION_ESTABLISHED = "Client is online.";
private static final String DONE = "Connection closed.";
private static final String IDENTITY = "CLIENT: ";
private BufferedReader systemin;
private boolean run;
public void establishConnection(int portNumber) throws UnknownHostException{
establishConnection(portNumber, InetAddress.getLocalHost().getHostAddress());
}
public void establishConnection(int portNumber, String hostName){
try(Socket clientSide = new Socket(hostName, portNumber);
PrintWriter outBound = new PrintWriter(clientSide.getOutputStream(), true);
BufferedReader inBound = new BufferedReader(
new InputStreamReader(clientSide.getInputStream()));){
outBound.println(CONNECTION_ESTABLISHED);
systemin = new BufferedReader(
new InputStreamReader(System.in));
run = true;
Thread clientOutputThread = new Thread() {
@Override
public void run() {
while(run) {
try {
outBound.println(systemin.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
};
clientOutputThread.start();
String next = inBound.readLine();
while(next!=null){
System.out.println(next);
next = inBound.readLine();
}
System.out.println(DONE);
run = false;
systemin.close();
} catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
BasicClient pc = new BasicClient();
pc.establishConnection(4454);
}
}