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);
|
157
|
42 selector.register(scs, SelectionKey.OP_ACCEPT, null);
|
|
43 } catch (IOException e1) {
|
166
|
44 return;
|
157
|
45 }
|
|
46
|
154
|
47 ns.writeLog("SessionManager starts mainroutin.", 1);
|
|
48
|
|
49 /* Main Loop */
|
|
50 while(running){
|
|
51
|
166
|
52 try {
|
|
53 selector.select();
|
154
|
54
|
166
|
55 for(SelectionKey key : selector.selectedKeys()){
|
154
|
56
|
166
|
57 if(key.isAcceptable()){
|
174
|
58 ns.writeLog("gets acceptable channel", 1);
|
166
|
59 REPServerSocketChannel<String> sc = (REPServerSocketChannel<String>) key.channel();
|
|
60 REPSocketChannel<String> channel;
|
157
|
61 channel = sc.accept1();
|
|
62 selector.register(channel, SelectionKey.OP_READ, null);
|
174
|
63 ns.writeLog("accepts a client.", 1);
|
166
|
64
|
|
65 }else if(key.isReadable()){
|
174
|
66 ns.writeLog("gets readable channel", 1);
|
166
|
67 //SelectableChannelSimulator<String> channel = key.channel();
|
|
68 REPSocketChannel<String> channel = (REPSocketChannel<String>) key.channel();
|
157
|
69 String packet;
|
|
70 packet = channel.read();
|
174
|
71 ns.writeLog("receives String==> `"+packet+"\'", 1);
|
166
|
72 channel.write("from SeMa"+this.getName()+": world");
|
157
|
73 }
|
154
|
74 }
|
|
75 }
|
166
|
76 catch (IOException e) { e.printStackTrace();}
|
154
|
77 }
|
166
|
78
|
154
|
79 }
|
|
80 }
|