-
Notifications
You must be signed in to change notification settings - Fork 0
/
YahtzeeServer.java
321 lines (300 loc) · 8.97 KB
/
YahtzeeServer.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
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
313
314
315
316
317
318
319
320
321
/*
* Course: CSC421
* Assignment: #3
* Author: Andrew Seligman
* Date: May 7, 2014
* File: YahtzeeServer.java
* Note: The code in this file has been adapted from
* SocketThrdServer.java, a file provided by Dr. Spiegel
*******************************************************************************/
import java.io.*;
import javax.swing.*;
import java.net.*;
/**
* The ServerData class holds data that is used by multiple threads
**/
class ServerData
{
final int minPlayers = 2;
final int maxPlayers = 5;
volatile int numConnected = 0;
volatile int numReadyToStart = 0;
volatile Worker[] Players = new Worker[maxPlayers];
volatile boolean[] Ready = new boolean[maxPlayers];
volatile String[] Names = new String[maxPlayers];
}
/**
* YahtzeeServer is the server for the Yahtzee applet. It provides a means for
* multiple Yahtzee applets to communicate.
**/
public class YahtzeeServer
{
static final int PORT = 0;
static ServerSocket server;
/**
* Initialize server data and accept new connections
**/
public static void main(String[] args)
{
ServerData Stats = new ServerData();
//set ready flag for all players to false
for(int idx = 0; idx < Stats.maxPlayers; idx++)
{
Stats.Ready[idx] = false;
}
try
{
server = new ServerSocket(PORT);
System.out.println("Server is running!");
}
catch(IOException e)
{
System.out.println("Server failed to listen on port");
System.exit(-1);
}
while(true)
{
Worker w;
try
{
//listen for new connections
w = new Worker(server.accept(), Stats);
System.out.println("New connection accepted: "+Stats.numConnected);
Thread t = new Thread(w);
t.start();
Thread.sleep(250);
}
catch(IOException ex)
{
System.out.println("Accept failed");
System.exit(-1);
}
catch(Exception ex)
{
System.out.println("Server Exception: sleep failed");
System.exit(-1);
}
}
}
/**
* Close the ServerSocket
**/
protected void finalize()
{
try
{
server.close();
}
catch(IOException e)
{
System.out.println("Could not close socket");
System.exit(-1);
}
}
}
/**
* The Worker class organizes player connections and communicates with
* applets to play the game.
**/
class Worker implements Runnable
{
Socket client;
ServerData stats;
BufferedReader in = null;
PrintWriter out = null;
int myIdx;
/**
* Constructor sets play order and adds this object to the Players array
**/
Worker(Socket newClient, ServerData Stats)
{
client = newClient;
this.stats = Stats;
if(stats.numConnected < stats.maxPlayers)
{
myIdx = stats.numConnected;
stats.Players[myIdx] = this;
stats.numConnected++;
}
else
{
//the maximum number of players is already connected
System.out.println("Too many players connected");
}
}
/**
* Wait for all players to give the ready signal before beginning the game
**/
public void run()
{
String word;
boolean allReady = false;
try
{//Thread.sleep(1000);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
Thread.sleep(1000);
out = new PrintWriter(client.getOutputStream(), true);
stats.Names[myIdx] = in.readLine();
}
catch(IOException ex)
{
System.out.println("Server IOException: IO failed");
System.exit(-1);
}
catch(Exception ex)
{
System.out.println("Server Exception in Worker");
System.exit(-1);
}
//check if this player is ready using a separate thread
SwingWorker BGworker = new SwingWorker(){
String value;
protected String doInBackground()
{
try
{
value = in.readLine();
System.out.println("BGworker"+myIdx+": "+value);
if(value.equals("READY"))
stats.Ready[myIdx] = true;
else
{
System.out.println("Server worked received "+
"unexpected value");
}
}
catch(IOException ex)
{//thrown when BGworker is cancelled
//System.out.println("BGworker IOException: IO failed");
}
catch(Exception ex)
{
System.out.println("Exception in SwingWorker");
ex.printStackTrace();
}
return null;
}
};
BGworker.execute();
while(!allReady)
{
try
{
Thread.sleep(1000);
if(stats.numConnected >= stats.maxPlayers)
{
//in case extra connections have been made
stats.numConnected = stats.maxPlayers;
allReady = true;
BGworker.cancel(true);
}
else if(stats.numConnected >= stats.minPlayers)
{
for(int idx = 0; idx < stats.numConnected; idx++)
{
if(stats.Ready[idx] == false)
break;
else if(idx == (stats.numConnected - 1))
{
allReady = true;
BGworker.cancel(true);
}
}
}
}
catch(Exception ex)
{
System.out.println("Server Exception in Worker: allReady loop");
System.exit(-1);
}
}
playGame();
}
/**
* Send player data to applets and begin broadcasting play choices
**/
public void playGame()
{
boolean isOver = false;
String message;
//signal client to begin game
//send order index, # players, and their names
try
{
out.println(""+myIdx);
out.println(""+stats.numConnected);
for(int idx = 0; idx < stats.numConnected; idx++)
{
while(stats.Names[idx] == null)
{//eliminate race condition where last player thread has not
//yet added its String to Names
Thread.sleep(1000);
}
out.println(stats.Names[idx]);
}
}
catch(Exception ex)
{
System.out.println("Server Exception in Worker: playGame "+myIdx);
ex.printStackTrace();
System.exit(-1);
}
while(!isOver)
{
try
{
message = in.readLine();
if(message.equals("GAMEOVER"))
isOver = true;
else
broadcast(message);
}
catch(IOException ex)
{
System.out.println("Server IOException: IO failed in playGame "+myIdx);
ex.printStackTrace();
System.exit(-1);
}
catch(Exception ex)
{
System.out.println("Server Exception in Worker: playGame");
ex.printStackTrace();
System.exit(-1);
}
}
if(myIdx == 0)
{
gameOver(stats);
System.out.println("Game complete. Ready for new game.");
}
//System.exit(0);
}
/**
* Reset the server data to begin a new game
*
* @param stats is the object containing server data
**/
public void gameOver(ServerData stats)
{
stats.numConnected = 0;
stats.numReadyToStart = 0;
stats.Players = new Worker[stats.maxPlayers];
stats.Names = new String[stats.maxPlayers];
//set ready flag for all players to false
for(int idx = 0; idx < stats.maxPlayers; idx++)
{
stats.Ready[idx] = false;
}
}
/**
* Send a String to each connected client
**/
public void broadcast(String message)
{
for(int idx = 0; idx < stats.numConnected; idx++)
{
stats.Players[idx].out.println(message);
}
System.out.println("Msg thread "+myIdx+": "+message);
}
}