-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClientThread.java
More file actions
98 lines (84 loc) · 2.99 KB
/
ClientThread.java
File metadata and controls
98 lines (84 loc) · 2.99 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
import java.io.*;
import java.net.*;
import IO.CommandParser;
import IO.IO;
import IO.Auth;
import Model.User;
import Model.GameMap;
import Utils.DB.DBUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
public class ClientThread extends Thread {
protected Socket socket;
private User user;
private String prompt = ">";
private Map<Integer, GameMap> maps;
private int id; // testing purpose
private Connection con;
public ClientThread(Socket clientSocket, Map<Integer, GameMap> maps, int id) {
this.socket = clientSocket;
this.maps = maps;
this.id = id;
}
public void run() {
BufferedReader input = null;
DataOutputStream output = null;
try {
// from javadoc:
// In general, each read request made of a Reader causes a
// corresponding read request to be made of the underlying
// character or byte stream. It is therefore advisable to wrap
// a BufferedReader around any Reader whose read() operations
// may be costly, such as FileReaders and InputStreamReaders.
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.err.println("Unable to create input or output pipe(s).");
return;
}
// print welcome message
IO out = new IO(output);
out.print("Welcome to Mud Game <933 Adventure>! Please login or register[login/register]:");
// create a sql connection for this thread
// TODO: this seems very vulnerable to DOS attack, maybe use a connection pool later
con = DBUtils.getNewConnection();
// login or register
user = new Auth(input, out, con).auth();
if(user == null) {
// System.out.println("User quit without login or register");
clientQuitPrepare();
return;
}
// user = User.getSampleUser(maps.get(0), id);
user.updateOutputStream(new IO(output));
user.print(user.getGameMap().welcome());
String line;
while (true) {
try {
user.print(prompt);
line = input.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
clientQuitPrepare();
return;
} else {
CommandParser.cmdParser(line, user);
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
public void clientQuitPrepare() {
try {
// release user in node, store update in db
if(user != null) user.quitPrepare(con);
con.close();
socket.close();
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}