-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuctionServer.java
316 lines (276 loc) · 6.5 KB
/
AuctionServer.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
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class AuctionServer implements Runnable
{
private static final long TIMER_LEN = 60000;
private static ServerSocket serverSock;
private static ArrayList<ClientHandler> clientList;
private Thread thread = null;
private boolean startAuction = true;
private AuctionItem curItem;
private ClientHandler curBidHolder = null;
private Timer timer;
/**
* Server class Constructor
* Initialises List of clienthandler objects
* Establishes Socket and calls start()
*/
public AuctionServer(int port)
{
clientList = new ArrayList<ClientHandler>();
try
{
serverSock = new ServerSocket(port);
start();
}
catch (IOException ioEx)
{
System.out.println("Unable to set up port " + port + "!");
System.exit(1);
}
}
/**
* Starts a Thread to run Server functionality. Ensures only one thread can run
*/
public void start()
{
if (thread == null)
{
thread = new Thread(this);
thread.start();
}
}
/**
* Removes reference to the current Thread.
* This will break the condition in run() and allow process to exit
*/
public void stop()
{
thread = null;
}
/**
* Main loop for this Server thread.
* Accepts new connections from clients and passes this socket to addThread()
* Once at two connections have been made, it starts the auction by getting an Item from the static list in AuctionItem
* This gets sent to all clients
* If a client joins while the auction is underway send the current item to it
*/
public void run()
{
while (thread != null)
{
try
{
addThread(serverSock.accept());
}
catch (IOException e)
{
// TODO Auto-generated catch block
System.out.println("Server accept error" + e);
stop();
}
if (clientList.size() == 2 && startAuction)
{
curItem = AuctionItem.getCurrentItem();
curItem.setStartTime(System.currentTimeMillis());
broadcastItem(curItem);
runTimer();
startAuction = false;
}
else if (!startAuction)
{
clientList.get(clientList.size() - 1).sendItem(curItem);
}
}
}
/*
* Instantiate a new clientHandler, add it to the clientList and start the Thread
*/
private void addThread(Socket socket)
{
clientList.add(new ClientHandler(socket, this));
clientList.get(clientList.size() - 1).start();
}
/*
* The timer is up so select the next Item to be sent to clients
* If Item has reached specs to be sold, mark as sold.
* If there are no more items to be sold, inform participants and close
*/
public void newAuctionItem()
{
if (curItem.getCurrentBid() >= curItem.getReservePrice())
{
curItem.setSold(true);
for (ClientHandler ch : clientList)
{
if (ch == curBidHolder)
{
ch.sendMsg("Congratulations! Your bid was successful for '" + curItem.getName() + "'\n\n");
}
else
{
ch.sendMsg("'" + curItem.getName() + "' has been sold to another user\n\n");
}
}
}
curItem = AuctionItem.nextItem();
if (curItem == null)
{
broadcastMsg("The Auction has concluded, thank you for participating\n");
}
else if (clientList.size() < 2)
{
broadcastMsg("The Auction will resume when there are at least two people\n");
}
else
{
curItem.setStartTime(System.currentTimeMillis());
broadcastItem(curItem);
runTimer();
}
}
public synchronized void broadcastMsg(String msg)
{
for (ClientHandler ch : clientList)
{
ch.sendMsg(msg);
}
}
/*
* Remove a client from the auction. Remove them from client list
* If there is only one person left, stop the auction
* This is synchronized so that somebody cannot leave the auction while an item is being broadcast
*/
public synchronized void leaveAuction(ClientHandler ch)
{
System.out.println("Person has left auction");
clientList.remove(ch);
try
{
ch.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
System.out.println("Error closing thread");
e.printStackTrace();
}
if (clientList.size() < 2)
{
startAuction = true;
}
notifyAll();
}
/*
* Send an item to all active clients
*/
public synchronized void broadcastItem(AuctionItem item)
{
for (ClientHandler ch : clientList)
{
ch.sendItem(item);
}
notifyAll();
}
/*
* Inform clients that there has been a new bid
* Inform successful bidders
*/
public synchronized void broadcastBidInfo()
{
for (ClientHandler ch : clientList)
{
if (ch == curBidHolder)
{
ch.sendMsg("Your bid is the current bid\n");
}
else
{
ch.sendMsg("There is a new bid\n");
}
}
notifyAll();
}
/*
* Handles successful new bids
* Resets the timer, notes the client and broadcasts the information to all clients
*/
public void newBid(String bidStr, ClientHandler ch)
{
double bid = Double.parseDouble(bidStr);
if (bid > curItem.getCurrentBid())
{
curItem.setCurrentBid(bid);
curItem.setStartTime(System.currentTimeMillis());
curBidHolder = ch;
broadcastBidInfo();
broadcastItem(curItem);
timer.cancel();
runTimer();
}
}
/*
* Create Timer. After the specified time, newAuctionItem() will be called.
* This timer will be cancelled and created again if a new Bid is made
*/
private void runTimer()
{
timer = new Timer("Countdown");
timer.schedule(new TimerTask() {
@Override
public void run()
{
// TODO Auto-generated method stub
newAuctionItem();
}
}, TIMER_LEN);
}
/*
* Loads the Items data from items.dat and creates instances of them into the static list in AuctionItem
*/
private static void loadData()
{
Scanner reader = null;
try
{
reader = new Scanner(new File("items.dat"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Unable to load Items");
}
String line = "";
String[] args = new String[2];
while (reader.hasNextLine())
{
line = reader.nextLine();
args = line.split("\t");
new AuctionItem(args[0], Double.parseDouble(args[1]));
}
reader.close();
}
/*
* Load the data and create instance of this class
*/
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.out.println("Usage: java AuctionServer port");
}
else
{
loadData();
new AuctionServer(Integer.parseInt(args[0]));
}
}
}