154
|
1 package test.channeltest;
|
|
2
|
|
3 import java.io.IOException;
|
157
|
4 import java.net.InetSocketAddress;
|
|
5 import java.net.SocketAddress;
|
|
6 import java.nio.channels.SelectionKey;
|
154
|
7 import java.util.LinkedList;
|
|
8
|
157
|
9 import rep.channel.REPLogger;
|
|
10 import rep.channel.REPSelector;
|
|
11 import rep.channel.REPServerSocketChannel;
|
|
12 import rep.channel.REPSocketChannel;
|
154
|
13
|
|
14 public class testSeMa extends Thread{
|
|
15
|
157
|
16 SocketAddress IP;
|
154
|
17 boolean running=true;
|
157
|
18 REPLogger ns;
|
|
19 LinkedList<REPSocketChannel<String>> channels;
|
166
|
20
|
161
|
21 public testSeMa(String name, String host, int port){
|
154
|
22 super(name);
|
157
|
23 IP = new InetSocketAddress(host,port);
|
161
|
24 ns = testNetworkSimulator.ns;
|
157
|
25 channels = new LinkedList<REPSocketChannel<String>>();
|
154
|
26 }
|
|
27 public void init(){
|
166
|
28
|
154
|
29 }
|
|
30
|
157
|
31 @SuppressWarnings("unchecked")
|
154
|
32 public void run() {
|
166
|
33 REPSelector selector;
|
157
|
34 REPServerSocketChannel<String> scs;
|
|
35 try {
|
166
|
36 selector = REPSelector.create();
|
157
|
37 scs = REPServerSocketChannel.<String>open();
|
166
|
38 scs.socket().setReuseAddress(true);
|
|
39 scs.socket().bind(IP);
|
|
40 scs.configureBlocking(false);
|
157
|
41 selector.register(scs, SelectionKey.OP_ACCEPT, null);
|
|
42 } catch (IOException e1) {
|
166
|
43 return;
|
157
|
44 }
|
|
45
|
154
|
46 ns.writeLog("SessionManager starts mainroutin.", 1);
|
|
47
|
|
48 /* Main Loop */
|
|
49 while(running){
|
|
50
|
166
|
51 try {
|
|
52 selector.select();
|
154
|
53
|
166
|
54 for(SelectionKey key : selector.selectedKeys()){
|
154
|
55
|
166
|
56 if(key.isAcceptable()){
|
|
57 ns.writeLog(this, "gets acceptable channel", 1);
|
|
58 REPServerSocketChannel<String> sc = (REPServerSocketChannel<String>) key.channel();
|
|
59 REPSocketChannel<String> channel;
|
157
|
60 channel = sc.accept1();
|
|
61 selector.register(channel, SelectionKey.OP_READ, null);
|
166
|
62 ns.writeLog(this, "accepts a client.", 1);
|
|
63
|
|
64 }else if(key.isReadable()){
|
|
65 ns.writeLog(this, "gets readable channel", 1);
|
|
66 //SelectableChannelSimulator<String> channel = key.channel();
|
|
67 REPSocketChannel<String> channel = (REPSocketChannel<String>) key.channel();
|
157
|
68 String packet;
|
|
69 packet = channel.read();
|
|
70 ns.writeLog(this, "receives String==> `"+packet+"\'", 1);
|
166
|
71 channel.write("from SeMa"+this.getName()+": world");
|
157
|
72 }
|
154
|
73 }
|
|
74 }
|
166
|
75 catch (IOException e) { e.printStackTrace();}
|
154
|
76 }
|
166
|
77
|
154
|
78 }
|
|
79 }
|