-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.java
121 lines (102 loc) · 2.68 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client{
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 3443;
private Socket client_socket;
private PrintWriter out;
private Scanner in;
private Scanner input;
private String name = "";
private Boolean flag;
public String getName(){
return this.name;
}
public Client(){
try{
client_socket = new Socket(SERVER_HOST, SERVER_PORT);
out = new PrintWriter(client_socket.getOutputStream());
in = new Scanner(client_socket.getInputStream());
input = new Scanner(System.in);
flag = false;
System.out.println("Connected");
System.out.println("All streams established");
}
catch (IOException ex){
ex.printStackTrace();
}
System.out.print("Enter your name: ");
name = input.nextLine();
System.out.println();
new Thread(new Runnable() {
@Override
public void run(){
try{
while (true){
if (in.hasNext()){
String message_from_server = in.nextLine();
if (message_from_server.toString().trim().equals("New member joined to server")){
System.out.println();
System.out.println("==========================");
System.out.println(message_from_server);
System.out.println();
}
else if (message_from_server.toString().trim().equals("<clients_number>")){
flag = true;
}
else if (flag = true){
System.out.println(message_from_server);
System.out.println();
System.out.println("==========================");
System.out.println();
flag = false;
}
else{
System.out.println(message_from_server);
}
}
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run(){
try{
while (true){
String message = input.nextLine();
if (message.equalsIgnoreCase("exit")){
try{
if (!name.isEmpty()){
out.println(name + " left the server");
}
else{
out.println("<unknown user> left the server");
}
out.println("exit");
out.flush();
out.close();
in.close();
client_socket.close();
System.out.println("All streams closed");
break;
}
catch (IOException ex){
ex.printStackTrace();
}
}
out.println(name + ": " + message);
out.flush();
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}).start();
}
}