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;
|
154
|
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(){
|
|
28
|
|
29 }
|
|
30
|
157
|
31 @SuppressWarnings("unchecked")
|
154
|
32 public void run() {
|
157
|
33 REPSelector selector = new REPSelector(null);
|
|
34 REPServerSocketChannel<String> scs;
|
|
35 try {
|
|
36 scs = REPServerSocketChannel.<String>open();
|
|
37 scs.socket().setReuseAddress(true);
|
|
38 scs.socket().bind(IP);
|
|
39 scs.configureBlocking(false);
|
|
40 selector.register(scs, SelectionKey.OP_ACCEPT, null);
|
|
41 } catch (IOException e1) {
|
|
42 }
|
|
43
|
154
|
44 ns.writeLog("SessionManager starts mainroutin.", 1);
|
|
45
|
|
46 /* Main Loop */
|
|
47 while(running){
|
|
48
|
|
49 try { selector.select(); }
|
|
50 catch (IOException e) { e.printStackTrace();}
|
|
51
|
157
|
52 for(SelectionKey key : selector.selectedKeys()){
|
154
|
53
|
|
54 if(key.isAcceptable()){
|
|
55 ns.writeLog(this, "gets acceptable channel", 1);
|
157
|
56 REPServerSocketChannel<String> sc = (REPServerSocketChannel<String>) key.channel();
|
|
57 REPSocketChannel<String> channel;
|
|
58 try {
|
|
59 channel = sc.accept1();
|
|
60 selector.register(channel, SelectionKey.OP_READ, null);
|
|
61 } catch (IOException e) {
|
|
62 }
|
154
|
63 ns.writeLog(this, "accepts a client.", 1);
|
|
64
|
|
65 }else if(key.isReadable()){
|
|
66 ns.writeLog(this, "gets readable channel", 1);
|
|
67 //SelectableChannelSimulator<String> channel = key.channel();
|
157
|
68 REPSocketChannel<String> channel = (REPSocketChannel<String>) key.channel();
|
|
69 try {
|
|
70 String packet;
|
|
71 packet = channel.read();
|
|
72 ns.writeLog(this, "receives String==> `"+packet+"\'", 1);
|
|
73 } catch (IOException e) {
|
|
74 }
|
154
|
75 channel.write("from SeMa"+this.getName()+": world");
|
|
76 }
|
|
77 }
|
|
78 }
|
|
79
|
|
80 }
|
|
81 }
|