-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerClient.java
More file actions
170 lines (151 loc) · 4.68 KB
/
ServerClient.java
File metadata and controls
170 lines (151 loc) · 4.68 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
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
class ServerClient {
static int lastClientId = 0;
int clientId;
ClientState state = ClientState.CONNECTING;
Socket socket;
InputStream in;
OutputStream out;
Thread thread;
/**
* Starts a new thread that runs {@link #connect()} to initialize the client, then listens for messages from the
* client indefinitely; see {@link #receiveMessage()}.
* <p>
* Once a message fails to be received or is invalid, stops listening for messages and calls {@link #disconnect()}.
*
* @param socket Socket to associate with the client.
*/
ServerClient(Socket socket) {
this.socket = socket;
thread = new Thread(() -> {
if (!connect()) {
System.out.printf("WARNING: %s failed to connect: %s\n", this,
socket.getInetAddress().getHostAddress());
return;
}
while (receiveMessage()) {
Thread.yield();
}
disconnect();
});
thread.start();
}
/**
* Builds and returns a string representation of the client, including client ID and special game state data
* (such as 'Winner', 'Player X', etc.).
*
* @return A string representation of the client.
*/
@Override
public String toString() {
String identifier = "Client #" + clientId;
if (Server.game.state == GameState.WAITING_ON_WINNER && Server.game.lastWinner == this) {
return identifier + " (Winner)";
}
if (Server.game.state == GameState.PLAYING) {
if (Server.game.playerX == this) {
return identifier + " (Player X)";
} else if (Server.game.playerO == this) {
return identifier + " (Player O)";
}
}
return identifier;
}
/**
* Sets up the client socket input and output streams, and calls the synchronized
* {@link Server#connect(ServerClient)} method for thread-safe server/game state updates.
*
* @return Boolean indicating success.
*/
boolean connect() {
state = ClientState.CONNECTING;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
disconnect();
return false;
}
if (!Server.connect(this)) {
disconnect();
return false;
}
state = ClientState.CONNECTED;
return true;
}
/**
* Closes the client socket and its input and output streams, and calls the synchronized
* {@link Server#disconnect(ServerClient)} method for thread-safe server/game state updates.
*/
void disconnect() {
if (state == ClientState.DISCONNECTING || state == ClientState.DISCONNECTED) {
return;
}
state = ClientState.DISCONNECTING;
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
in = null;
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
out = null;
}
if (socket == null) {
return;
}
try {
socket.close();
} catch (IOException e) {
// ignore
}
Server.disconnect(this);
socket = null;
state = ClientState.DISCONNECTED;
}
/**
* Waits for a byte from the client by calling {@link InputStream#read()}, then sends the received byte over to the
* {@link Server#receiveMessage(ServerClient, int)} method for thread-safe server/game state updates.
*
* @return Boolean indicating success.
*/
boolean receiveMessage() {
if (state != ClientState.CONNECTED) {
return false;
}
try {
int nextByte;
if ((nextByte = in.read()) == -1) {
return false;
}
return Server.receiveMessage(this, nextByte);
} catch (IOException e) {
// ignore
}
return false;
}
/**
* Sends a message to the client.
*/
void sendMessage(byte[] bytes) {
try {
out.write(bytes);
} catch (IOException e) {
if (state != ClientState.DISCONNECTING) {
System.out.printf("ERROR: Failed to send message to %s: %s\n", this, Arrays.toString(bytes));
System.exit(-1);
}
}
}
}