-
Notifications
You must be signed in to change notification settings - Fork 0
/
LotteryServerC.java
executable file
·86 lines (73 loc) · 2.25 KB
/
LotteryServerC.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
package f12;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Random;
public class LotteryServerC implements Runnable{
private String[] winningTickets = {"111111","222222","333333","444444","555555","666666","777777","888888","999999"};
private Thread server = new Thread(this);
private DatagramSocket socket;
private Random rand = new Random();
public LotteryServerC(int port) throws SocketException {
socket = new DatagramSocket(port);
server.start();
}
public void run() {
DatagramPacket packet;
byte[] buffer = new byte[256];
String ticket;
System.out.println("Server running");
while(true) {
try {
packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
ticket = new String(packet.getData(),0,packet.getLength());
new ClientHandler(packet.getAddress(), packet.getPort(), ticket);
} catch(Exception e) {
System.err.println(e);
}
}
}
private String getResponse(String ticket) {
randomPause();
return checkTicket(ticket);
}
private void randomPause() {
try {
Thread.sleep(rand.nextInt(4)*1000);
} catch (InterruptedException e) {}
}
// synchronisering behövs ofta då flera trådar använder samma resurs (ej i detta fall)
private synchronized String checkTicket(String ticket) {
for(int i=0; i<winningTickets.length; i++) {
if(ticket.equals(winningTickets[i])) {
return "VINST";
}
}
return "NIT";
}
private class ClientHandler extends Thread {
private InetAddress address;
private int port;
private String ticket;
public ClientHandler(InetAddress address, int port, String ticket) {
this.address = address;
this.port = port;
this.ticket = ticket;
start();
}
public void run() {
String response = getResponse(ticket);
byte[] outData = response.getBytes();
DatagramPacket packet = new DatagramPacket(outData, outData.length, address, port);
try {
socket.send(packet);
} catch (IOException e) {}
}
}
public static void main(String[] args) throws SocketException {
new LotteryServerC(3462);
}
}