84
|
1 package pathfinder.BlockingQ;
|
|
2
|
|
3 import java.util.ArrayList;
|
|
4 import java.util.List;
|
|
5
|
|
6 public class SeMaSimulator<P> extends Thread {
|
|
7 private int MAX_PACKET;
|
|
8 private int MAX_CLIENT;
|
|
9 private boolean running=true;
|
|
10 private NetworkSimulator<P> ns;
|
|
11 private List<ChannelSimulator<P>> csList;
|
|
12
|
|
13 public SeMaSimulator(NetworkSimulator<P> _ns, int max_client, int max_packet){
|
|
14 ns = _ns;
|
|
15 MAX_CLIENT = max_client;
|
|
16 MAX_PACKET = max_packet;
|
|
17 csList = new ArrayList<ChannelSimulator<P>>();
|
|
18 }
|
|
19 public SeMaSimulator(NetworkSimulator<P> _ns){
|
|
20 this(_ns, 2, 0);
|
|
21 }
|
|
22
|
|
23 synchronized public void finish(){
|
|
24 synchronized(ns){
|
|
25 running = false;
|
|
26 ns.notify();
|
|
27 }
|
|
28 }
|
|
29
|
|
30 /**
|
|
31 * Check whether the NetworkSimulator hold waiting connections.
|
|
32 */
|
|
33 private void checkAccept(){
|
|
34 ChannelSimulator<P> cs;
|
|
35 while((cs=ns.accept())!=null){
|
|
36 csList.add(cs);
|
|
37 }
|
|
38 }
|
|
39
|
|
40 public void run(){
|
|
41 int i=0;
|
|
42 int count=0;
|
|
43 P packet;
|
|
44
|
|
45 while(csList.size()<MAX_CLIENT){ checkAccept(); Thread.yield(); }
|
|
46 System.out.println("SessionManager start.");
|
|
47
|
|
48 /* Main Loop */
|
|
49 ChannelSimulator<P> cs = csList.get(i);
|
|
50 while(running
|
|
51 && (MAX_PACKET==0 || count<MAX_PACKET)){
|
|
52 synchronized(ns){
|
|
53 int prev_i=i;
|
|
54 while((packet=cs.poll())==null && running){
|
|
55 i = (i+1)%csList.size(); // i++
|
|
56 cs = csList.get(i); // 次のChennelをゲット
|
|
57 if(i==prev_i) try { ns.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
|
|
58 }
|
|
59 }
|
|
60 if(!running) break;
|
|
61
|
|
62 System.out.println("SeMa pass packet to "+i+":>> "+packet.toString());
|
|
63 i = (i+1)%csList.size(); // i++
|
|
64 cs = csList.get(i); // 次のChennelをゲット
|
|
65
|
|
66 // readできていたならそれを書き込む
|
|
67 try {
|
|
68 cs.write(packet);
|
|
69 } catch (InterruptedException e) {
|
|
70 System.out.println("SeMa cannot write!!");
|
|
71 e.printStackTrace();
|
|
72 }
|
|
73 count++;
|
|
74 }
|
|
75 /*
|
|
76 ChannelSimulator<P> cs = csList.get(i);
|
|
77 while(running
|
|
78 && MAX_PACKET==0 || count<MAX_PACKET){
|
|
79 packet=cs.poll(); // [i]からread
|
|
80 //if(packet!=null) System.out.println("SeMa catch packet to "+i+":>> "+packet.toString());
|
|
81 i = (i+1)%csList.size(); // i++
|
|
82 cs = csList.get(i); // 次のChennelをゲット
|
|
83 if (packet!=null) {
|
|
84 System.out.println("SeMa pass packet to "+i+":>> "+packet.toString());
|
|
85 cs.write(packet); // readできていたならそれを書き込む
|
|
86 count++;
|
|
87 }
|
|
88 //if (i==0) checkAccept(); //全部回ったらaccept待ちをチェック
|
|
89 }
|
|
90 */
|
|
91 System.out.println("SessionManager finish.");
|
|
92 }
|
|
93 }
|