-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLotteryServerF.java
executable file
·84 lines (73 loc) · 2.22 KB
/
LotteryServerF.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
package f12;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class LotteryServerF implements Runnable{
private String[] winningTickets = {"111111","222222","333333","444444","555555","666666","777777","888888","999999"};
private Thread server = new Thread(this);
private ServerSocket serverSocket;
private Random rand = new Random();
private RunOnThreadN pool;
public LotteryServerF(int port, int nbrOfThreads) throws IOException {
pool = new RunOnThreadN(nbrOfThreads);
serverSocket = new ServerSocket(port);
pool.start();
server.start();
}
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";
}
public void run() {
System.out.println("Server running");
while(true) {
try {
Socket socket = serverSocket.accept();
pool.execute(new ClientHandler(socket));
} catch(IOException e) {
System.err.println(e);
}
}
}
private class ClientHandler implements Runnable {
private Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
String ticket,response;
System.out.println("Klient uppkopplad");
try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream()) ) {
ticket = dis.readUTF();
response = getResponse(ticket);
dos.writeUTF(response);
dos.flush();
} catch(IOException e) {}
try {
socket.close();
} catch(Exception e) {}
System.out.println("Klient nerkopplad");
}
}
public static void main(String[] args) throws IOException {
new LotteryServerF(3465,50);
}
}