forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleServer.java
More file actions
181 lines (169 loc) · 5.85 KB
/
SimpleServer.java
File metadata and controls
181 lines (169 loc) · 5.85 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
/**
* Java. Level 2. Lesson 8
* Simple server for chat
*
* @author Sergey Iryupin
* @version 0.3.3 dated Jun 29, 2018
*/
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
class SimpleServer implements IConstants {
List<ClientHandler> clients; // list of clients
public static void main(String[] args) {
new SimpleServer();
}
SimpleServer() {
ClientHandler client;
clients = new ArrayList<>();
System.out.println(SERVER_START);
try (ServerSocket server = new ServerSocket(SERVER_PORT)) {
new Thread(new CommandHandler(server)).start(); // command to server
while (true) {
Socket socket = server.accept();
synchronized (clients) {
client = new ClientHandler(socket, clients.size() + 1);
clients.add(client); // adding new client in the list
System.out.println("#" + (clients.size()) + CLIENT_JOINED);
}
new Thread(client).start();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println(SERVER_STOP);
}
/**
* checkAuthentication: check login and password
*
* @param login for checking
* @param passwd for checking
*
* @return if the pair login/passwd is found in the database,
* authentication is successful
*/
private boolean checkAuthentication(String login, String passwd) {
boolean result = false;
try {
// loads a class, including running its static initializers
Class.forName(DRIVER_NAME);
// connect db
Connection connect = DriverManager.getConnection(SQLITE_DB);
// looking for login && passwd in db
PreparedStatement pstmt = connect.prepareStatement(SQL_SELECT);
// replace "?" to the login
pstmt.setString(1, login);
// returns ResultSet object generated by the query
ResultSet rs = pstmt.executeQuery();
// process rows from the query result
while (rs.next())
result = rs.getString(PASSWD_COL).equals(passwd);
// close all
rs.close();
pstmt.close();
connect.close();
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
return false;
}
return result;
}
/**
* CommandHandler: processing of commands from server console
*/
class CommandHandler implements Runnable {
ServerSocket server;
Scanner scanner;
CommandHandler(ServerSocket server) {
this.server = server;
scanner = new Scanner(System.in);
}
@Override
public void run() {
String command;
do
command = scanner.nextLine();
while (!command.equalsIgnoreCase(EXIT_COMMAND));
try {
server.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
/**
* broadcastMsg: sending a message to all clients
*/
private void broadcastMsg(String msg) {
synchronized (clients) {
for (ClientHandler client : clients)
client.sendMsg(msg);
}
}
/**
* ClientHandler: service requests of clients
*/
class ClientHandler implements Runnable {
BufferedReader reader;
PrintWriter writer;
Socket socket;
String name;
ClientHandler(Socket clientSocket, int counter) {
try {
socket = clientSocket;
reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
name = "Client #" + counter;
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
/**
* sendMsg: sending a message to the client
*/
private void sendMsg(String msg) {
try {
writer.println(msg);
writer.flush();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
@Override
public void run() {
String message;
try {
do {
message = reader.readLine();
if (message != null) {
System.out.println(name + ": " + message);
if (message.startsWith(AUTH_SIGN)) {
String[] wds = message.split(" ");
if (checkAuthentication(wds[1], wds[2])) {
name = wds[1];
sendMsg("Hello, " + name);
sendMsg("\0");
} else {
System.out.println(name + ": " + AUTH_FAIL);
sendMsg(AUTH_FAIL);
message = EXIT_COMMAND;
}
} else if (!message.equalsIgnoreCase(EXIT_COMMAND)) {
broadcastMsg(name + ": " + message);
broadcastMsg("\0");
}
}
} while (!message.equalsIgnoreCase(EXIT_COMMAND));
synchronized (clients) {
clients.remove(this); // delete client from list
}
socket.close();
System.out.println(name + CLIENT_DISCONNECTED);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}