Java-Gaming.org
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
Featured games (78)
games approved by the League of Dukes
Games in Showcase (406)
games submitted by our members
Games in WIP (293)
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 791 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.

Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
 
Get high quality music tracks for your game!

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

The first screenshot will be displayed as a thumbnail.

The invasion has landed! On Mars! And you're there to beat 'em!
cubemaster21 (84 views)
2013-05-17 21:29:12

alaslipknot (92 views)
2013-05-16 21:24:48

gouessej (124 views)
2013-05-16 00:53:38

gouessej (117 views)
2013-05-16 00:17:58

theagentd (127 views)
2013-05-15 15:01:13

theagentd (114 views)
2013-05-15 15:00:54

StreetDoggy (158 views)
2013-05-14 15:56:26

kutucuk (180 views)
2013-05-12 17:10:36

kutucuk (180 views)
2013-05-12 15:36:09

UnluckyDevil (187 views)
2013-05-12 05:09:57
Complex number cookbook
by Roquen
2013-04-24 12:47:31

2D Dynamic Lighting
by Oskuro
2013-04-17 16:46:12

2D Dynamic Lighting
by Oskuro
2013-04-17 16:45:57

2D Dynamic Lighting
by Oskuro
2013-04-17 16:23:20

Noise (bandpassed white)
by Roquen
2013-04-05 17:36:01

Noise (bandpassed white)
by Roquen
2013-04-03 16:17:38

Java Data structures
by Roquen
2013-03-29 13:21:12

Topic Request
by kutucuk
2013-03-22 21:42:01
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!
Page created in 0.445 seconds with 20 queries.