Java-Gaming.org    
Featured games (78)
games approved by the League of Dukes
Games in Showcase (426)
Games in Android Showcase (89)
games submitted by our members
Games in WIP (466)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Check my first NIO code  (Read 915 times)
0 Members and 1 Guest are viewing this topic.
Offline qgpr

Senior Newbie




yawn


« Posted 2005-01-22 22:36:58 »

I have read this tutorial several times,
http://grexengine.com/sections/externalgames/articles/Adam%20Martin-Java%20NIO%20Networking%20for%20Games-2.html
as well as others, and came up with this, I would like you to tell me if I am doing anything wrong as well as answering some points I still don't get (check comments).

What I think is having the User class hold the data (ArrayList<String> TxMessages;) to be sent to that user. Using a Hasmap<SelectionKey, User> to find out who's user the selectionkey belongs to I guess.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
public class NIOClass {

      public NIOCLass (int port) {
            ConnSelector = Selector.open();
            RxSelector = Selector.open();
            TxSelector = Selector.open();
            charset = Charset.forName("UTF-8");
            TxPort = port;
            RxPort = port;
            init();
      }

      public void init() {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking( false );

            ServerSocket ss = ssc.socket();
            InetSocketAddress address = new InetSocketAddress(RxPort);
            ss.bind(address);
           
            //SelectionKey key = ssc.register(RxSelector, SelectionKey.OP_READ);
           //So I register the same channel + port with different selectors depending on their behavior
           ssc.register(ConnSelector, SelectionKey.OP_ACCEPT);
            ssc.register(RxSelector, SelectionKey.OP_READ);
            ssc.register(TxSelector, SelectionKey.OP_WRITE);
      }
     
     
//Serve for at least <minimum_time> as stop as soon as possible after serving for <maximum_time>
     public void serve (int minimum_time, int maximum_time) {
            long currentTime = System.currentTimeMillis();
            long minTime = currentTime + minimum_time;
            long maxTime = currentTime + maximum_time;
           
            boolean keepGoing = true;
            while (keepGoing) {
                  ConnSelector.selectNow();
                  Set keys = ConnSelector.selectedKeys();
                  if(keys.isEmpty()) {
                        TxSelector.selectNow();
                        keys = TxSelector.selectedKeys();
                  };
                  if(keys.isEmpty()) {
                        RxSelector.selectNow();
                        keys = RxSelector.selectedKeys();
                  }
                  Iterator it = keys.iterator();
                  while (keepGoing) {
                        if(it.hasNext()) {
                              SelectionKey key = (SelectionKey)it.next();
                              it.remove();
                             
                              //processkey();
                             if(key.isAcceptable()) {
                                    /* Banned IPs?
                                    * Maximum # of connections per IP?
                                    */

                                    ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                                    SocketChannel sc = ssc.accept();
                                   
                                    sc.configureBlocking(false);
                                    sc.socket().setTcpNoDelay(true); // will this work or bring problems, what happens if two messages arrive for the same socket before I read.

                                    //SelectionKey newKey = sc.register(RxSelector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
                                   keys.add(sc.register(RxSelector, SelectionKey.OP_READ)); // keys.add(), is it necessary?, I saw it somewhere else.
                                   sc.register(TxSelector, SelectionKey.OP_WRITE);
                                    //and add the SelectionKeys to the respective User class
                             } else if(key.isWritable()) {
                                    //get respective User class from a hashmap or whatever
                                   String message;
                                    //message = User.TxMessages.next();
                                   ByteBuffer bb = charset.encode(message);
                                   
                                    WritableByteChannel wbc = (WritableByteChannel)key.channel();
                                    SocketChannel sc;
                                    wbc.write(bb);
                              } else if(key.isReadable()) {
                                    ReadableByteChannel rbc = (ReadableByteChannel) key.channel();
                                   
                                    ByteBuffer bb = null;
                                    bb = (ByteBuffer) key.attachment();
                                    if(bb == null) {
                                          // attach InputBuffer to key
                                         bb = ByteBuffer.allocate(1024);
                                          key.attach(bb);
                                    } else {
                                          // If we already had an inputBuffer, we need to make sure it's ready for use (what does this do?)
                                         bb.limit(bb.capacity());
                                    }
                                   
                                    int numBytesRead = rbc.read(bb);
                                    if(numBytesRead < 0) {
                                          // This is an undocumented feature - it means the client has disconnected
                                         key.cancel();
                                          key.channel().close();
                                    } else {
                                          while( /*there_are_still_requests_in_the_buffer*/ true ) {
                                                // Process the first request
                                               // Remove the first request
                                         }
                                    }

                                    rbc.read(bb);                                    
                                    String text = charset.decode(bb).toString();
                                    //do something
                             }
                             
                             
                        };                        
                        currentTime = System.currentTimeMillis();
                        if(currentTime > minTime) keepGoing = false;
                        if(currentTime > maxTime) keepGoing = false;
                  }
            }
            return;
      }
     
      public void write(User user, String message) {
            //User.TxMessages.add(message);
     }

      private int TxPort;
      private int RxPort;
      private java.nio.channels.Selector ConnSelector;
      private java.nio.channels.Selector RxSelector;
      private java.nio.channels.Selector TxSelector;
      Charset charset;
}
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (74 views)
2014-04-15 18:08:23

BurntPizza (68 views)
2014-04-15 03:46:01

UprightPath (80 views)
2014-04-14 17:39:50

UprightPath (65 views)
2014-04-14 17:35:47

Porlus (81 views)
2014-04-14 15:48:38

tom_mai78101 (105 views)
2014-04-10 04:04:31

BurntPizza (165 views)
2014-04-08 23:06:04

tom_mai78101 (261 views)
2014-04-05 13:34:39

trollwarrior1 (210 views)
2014-04-04 12:06:45

CJLetsGame (220 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!