-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathClient.java
More file actions
312 lines (271 loc) · 10.3 KB
/
Client.java
File metadata and controls
312 lines (271 loc) · 10.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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package arhangel.dim.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import arhangel.dim.core.messages.ChatCreateMessage;
import arhangel.dim.core.messages.ChatHistoryMessage;
import arhangel.dim.core.messages.ChatHistoryResultMessage;
import arhangel.dim.core.messages.ChatListMessage;
import arhangel.dim.core.messages.ChatListResultMessage;
import arhangel.dim.core.messages.InfoMessage;
import arhangel.dim.core.messages.InfoResultMessage;
import arhangel.dim.core.messages.LoginMessage;
import arhangel.dim.core.messages.Message;
import arhangel.dim.core.messages.StatusMessage;
import arhangel.dim.core.messages.TextMessage;
import arhangel.dim.core.messages.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import arhangel.dim.container.Container;
import arhangel.dim.container.InvalidConfigurationException;
import arhangel.dim.core.net.ConnectionHandler;
import arhangel.dim.core.net.Protocol;
import arhangel.dim.core.net.ProtocolException;
public class Client implements ConnectionHandler {
private Long userId;
static Logger log = LoggerFactory.getLogger(Client.class);
private Protocol protocol;
private int port;
private String host;
private Thread socketThread;
private Socket socket;
private InputStream in;
private OutputStream out;
public Protocol getProtocol() {
return protocol;
}
public InputStream getIn() {
return in;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
public void initSocket() throws IOException {
socket = new Socket(host, port);
in = socket.getInputStream();
out = socket.getOutputStream();
socketThread = new Thread(() -> {
final byte[] buf = new byte[1024 * 500];
log.info("Starting listener thread...");
while (!Thread.currentThread().isInterrupted()) {
try {
// Здесь поток блокируется на ожидании данных
int read = in.read(buf);
if (read > 0) {
// По сети передается поток байт, его нужно раскодировать с помощью протокола
Message msg = protocol.decode(Arrays.copyOf(buf, read));
onMessage(msg);
}
} catch (Exception e) {
log.error("Failed to process connection: {}", e);
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
});
socketThread.start();
}
@Override
public void onMessage(Message msg) {
switch (msg.getType()) {
case MSG_STATUS:
StatusMessage statusMsg = (StatusMessage) msg;
if (statusMsg.getStatus().equals("Logged in")) {
this.setUserId(statusMsg.getSenderId());
log.info("You logged in as user with id = " + statusMsg.getSenderId().toString());
} else if (statusMsg.getStatus().equals("Chat created")) {
log.info("You created a chat");
} else {
log.info("Recieved: " + statusMsg.getStatus());
}
break;
case MSG_CHAT_LIST_RESULT:
ChatListResultMessage resultMessage = (ChatListResultMessage) msg;
log.info(resultMessage.getChatsIdList().toString());
break;
case MSG_CHAT_HIST_RESULT:
ChatHistoryResultMessage resultHistory = (ChatHistoryResultMessage) msg;
log.info(resultHistory.getMessagesInChatId().toString());
break;
case MSG_INFO_RESULT:
InfoResultMessage infoResult = (InfoResultMessage) msg;
log.info("About user: "
+ "Login: " + infoResult.getLogin()
+ " Password: " + infoResult.getPassword());
break;
default: log.error("Unknown recieved message");
}
}
public boolean checkArgNum(String[] strings, int num) {
if (strings.length < num) {
log.error("Not enough arguments");
return false;
} else if (strings.length > num) {
log.error("Too many arguments");
return false;
}
return true;
}
public boolean isLoggedIn() {
if (userId == null) {
return false;
}
else {
return true;
}
}
public boolean processInput(String line) throws IOException, ProtocolException {
String[] tokens = line.split(" ");
String cmdType = tokens[0];
switch (cmdType) {
case "/login":
if (!checkArgNum(tokens, 3)) {
return false;
}
LoginMessage msg = new LoginMessage();
msg.setType(Type.MSG_LOGIN);
msg.setLogin(tokens[1]);
msg.setPassword(tokens[2]);
send(msg);
return true;
case "/text":
if (!checkArgNum(tokens, 3)) {
return false;
}
TextMessage textMessage = new TextMessage();
if (!isLoggedIn()) {
log.error("Can't send a message while not logged in");
return false;
}
textMessage.setSenderId(this.getUserId());
textMessage.setType(Type.MSG_TEXT);
textMessage.setChatId(Long.parseLong(tokens[1]));
textMessage.setText(tokens[2]);
send(textMessage);
return true;
case "/help":
log.info("Messenger v 1.0" +
"Type:" +
"1) /login to log in" +
"2) /text to send a message" +
"3) /chat_list to recieve chats you are in");
return true;
case "/info":
if (!isLoggedIn()) {
log.error("Anonymous can't get info about users");
return false;
}
InfoMessage infomsg = new InfoMessage();
infomsg.setType(Type.MSG_INFO);
if (tokens.length == 1) {
log.debug("Self-information case");
infomsg.setUsrId(this.getUserId());
} else {
log.info(tokens[1]);
infomsg.setUsrId(Long.parseLong(tokens[1]));
}
send(infomsg);
return true;
case "/chat_list":
if (!isLoggedIn()) {
log.error("Can't check chat list for anonymous");
return false;
}
if (tokens.length > 1) {
log.error("Too many arguments");
}
ChatListMessage chatListMessage = new ChatListMessage(this.userId);
send(chatListMessage);
return true;
case "/chat_create":
if (!isLoggedIn()) {
log.error("Can't check chat list for anonymous");
return false;
}
if (!checkArgNum(tokens, 2)) {
return false;
}
String[] users = tokens[1].split(",");
List<Long> userIdList = new ArrayList<>();
for (String s : users) userIdList.add(Long.valueOf(s));
ChatCreateMessage chatCreateMessage = new ChatCreateMessage(userIdList);
send(chatCreateMessage);
return true;
case "/chat_history":
if (!isLoggedIn()) {
log.error("Can't get chat history for anonymous");
return false;
}
if (!checkArgNum(tokens, 2)) {
return false;
}
ChatHistoryMessage chatHistoryMessage = new ChatHistoryMessage(Long.parseLong(tokens[1]));
send(chatHistoryMessage);
return true;
default:
log.error("Unknown input command: " + line);
return false;
}
}
@Override
public void send(Message msg) throws IOException, ProtocolException {
log.info(msg.toString());
out.write(protocol.encode(msg));
out.flush();
}
@Override
public void close() throws IOException, InterruptedException {
if ( !socket.isClosed()) {
socket.close();
}
if (!socketThread.isInterrupted()) {
socketThread.interrupt();
socketThread.join();
}
}
public static void main(String[] args) throws Exception {
Client client = null;
try {
Container context = new Container("client.xml");
client = (Client) context.getByName("client");
} catch (InvalidConfigurationException e) {
log.error("Failed to create client", e);
return;
}
try {
client.initSocket();
Scanner scanner = new Scanner(System.in);
System.out.println("$");
byte[] buf = new byte[1024 * 500];
while (true) {
String input = scanner.nextLine();
if ("q".equals(input)) {
return;
}
try {
if (!client.processInput(input)) {
continue;
}
} catch (ProtocolException | IOException e) {
log.error("Failed to process user input", e);
}
// int readBytes = client.getIn().read(buf);
// Message msg = client.getProtocol().decode(buf);
}
} catch (Exception e) {
log.error("Application failed.", e);
} finally {
if (client != null) {
client.close();
}
}
}
}