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