Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (491)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (555)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: jonjava (posted 2012-04-16 20:08:32, viewed 124 times)

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   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   240   241   242   243   244   245   246   247   248   249   250   251   252   253   254   255   256   257   258   259   260   261   262   263   264   265   266   267   268   269   270   271   272   273   274   275   276   277   278   279   280   281   282   283   284   285   286   287   288   289   290   291   292   293   294   295   296   297   298   299   300   301   302   303   304   305   306   307   308   309   310   311   312   313   314   315   316   317   318   319   320   321   322   323   324   325   326   327  
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.net.*;
import java.util.Iterator;

/**
 * A non-blocking Server utilizing java.nio Channels
 * instead of the old/typical 1 Thread per Client method.
 * 
 * Extend and Override handleAccept(), handleRead() and or 
 * ChannelClient helper class to implement your own protocol.
 * 
 * @author Ada
 * 
 */
public class ChannelServer  implements Runnable {
   
   private final ServerSocketChannel serverChannel;
   private final ServerSocket serverSocket;
   
   private ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
   
   private final int PORT;
   
   private final Selector selector;
   
   /**
    * Initialize the Server.
    * @param Port Number to listen to.
    */
   public ChannelServer (int PORT) throws IOException
   {
       // this.buffer.order(ByteOrder.BIG_ENDIAN);
      
      // System.out.println(Charset.defaultCharset().name());
      
      this.PORT = PORT;
      this.serverChannel = ServerSocketChannel.open();
      this.serverSocket = this.serverChannel.socket();
      this.selector = Selector.open();
      
      // Bind the server to specified port.
      this.serverSocket.bind(new InetSocketAddress( this.PORT ));
      
      // Configure non-blocking mode.
      this.serverChannel.configureBlocking(false);
      
      // Register the channel on the selector and save the key.
      this.serverChannel.register(selector, SelectionKey.OP_ACCEPT);
   }
   
   /**
    * Start the Server.
    */
   public void start()
   {
      Thread t = new Thread( this );
      t.start();
   }
   
   @Override
   public void run() {
      try {
         int n;
         
         while(true)
         {
            // Check Channels for readiness.
            n = this.selector.select(); // Block until there's data.
            
            if (n == 0) {
               continue; // No data to handle
            }
            
            // Get an iterator over the selected keys
            Iterator it = this.selector.selectedKeys().iterator();
            
            while( it.hasNext( ) ) {
               // Get the SelectionKey
               SelectionKey key = (SelectionKey) it.next();
               
               if (key.isAcceptable( )) {
                  // Accept a new client.
                  this.handleAccept( key );
               }
               if ( key.isReadable() ) {
                  // Read Data from Client.
                  this.handleRead( key );
               }
               
               // Remove the key from selected keys.
               it.remove();
            }
         }
      }
      catch(Exception e) {
         System.out.println(e);
         e.printStackTrace();
      }
   }

   
   /**
    * Register a Channel to a specific Selector
    * and create a helper client object
    * to handle communication.
    * @param selector Selector.
    * @param channel SocketChannel.
    * @param opRead interested Ops.
    * @param client helper client object.
    * @throws IOException 
    */
   private void registerChannel(Selector selector, SocketChannel channel,
         int opRead, ChannelClient client ) throws IOException {
      channel.register(this.selector, SelectionKey.OP_READ, client);
      // Greet the new connection.
      channel.write(ByteBuffer.wrap("Hello!\r\n".getBytes()));
   }

   /**
    * Decide what to do with the data client has sent.
    * @param key The SelectionKey from the Selector.
    */
   public void handleRead( SelectionKey key )
   {
      // System.out.println("In handleRead()");
      
      ChannelClient client = ((ChannelClient) key.attachment());
      if (client != null)
         client.handleMessage(this.buffer);
      
   }
   
   /**
    * Handle a new connection-
    * @param key The SelectionKey from the Selector.
    * @throws IOException 
    */
   public void handleAccept( SelectionKey key ) throws IOException
   {
      ServerSocketChannel server = 
            (ServerSocketChannel) key.channel( );
      SocketChannel channel = server.accept( );
      
      // Make sure that a client connected.
      if(channel == null) return;
      System.out.println("New Client Connected!");
      
      // Set the channel into non-blocking mode.
      channel.configureBlocking(false);
      
      // Register client (channel) for Reading.
      // Also create new helper class to handle communcations with the client.
      registerChannel( this.selector, channel, SelectionKey.OP_READ, new ChannelClient(channel) );
      
   }
   
   public static void main(String [] argv) {
      int port = 7; // Default port.
      
      if ( argv.length > 0 ) {
         port = Integer.parseInt(argv[1]);
      }
      
      System.out.println("Starting server..");
      
      try {
         new ChannelServer(port).start();
      }
      catch(Exception e){
         e.printStackTrace();
         System.out.println(e);
      }
   }
   
   
}



//
//
//




import java.io.IOException;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.net.*;

import java.util.Date;
import java.util.regex.Pattern;

/**
 * Helper class to handle client specific communication.
 * @author Ada
 *
 */

public class ChannelClient {
   
   private final SocketChannel channel;
   private String message = "";
   protected static Charset cs = Charset.forName("utf-8");
   
   public ChannelClient(SocketChannel channel) {
      this.channel = channel;
   }
   
   public void handleMessage(ByteBuffer buffer)  {
      
      // System.out.println("Data received from Client.");
      
      // Clear Buffer.
      buffer.clear();
      
      int count = 0;
      // Fill buffer with some data.
      try {
         count = channel.read(buffer);
      } catch (IOException e) {
         e.printStackTrace();
      }
      
      if (count < 0) {
         // EOS
         this.close();
      }
      if (count <= 0) {
         // No data to handle.
         return;
      }
      
      // Flip buffer for reading.
      buffer.flip();
      
      // Interpret the byte data as utf-8 characters.
      CharBuffer buf = cs.decode(buffer);
      message += buf;
      
      // Lazy way of checking for new line
      String[] strings = message.split("$");
      
      System.out.print(buf);
      
      
      // Respond only after a new line occurs.
      if(strings.length > 1) {

         this.interpretMessage(message);
         
         message = "";
         strings = null;
      }
   }
   
   private void interpretMessage(String message) {
      
      boolean echo = false;
      
      Pattern quitPattern = 
            Pattern.compile("(q|quit|bye|goodbye|leave|pois|poistu){1}$*", Pattern.CASE_INSENSITIVE);
      Pattern timePattern = 
            Pattern.compile("(time|aika|date){1}$*", Pattern.CASE_INSENSITIVE);
      Pattern greetPattern = 
            Pattern.compile("(hello|hi|terve|moro|moi|moikka|moromoro|greet|greetings|good day|salutations){1}$*", 
                  Pattern.CASE_INSENSITIVE);
      Pattern helpPattern = 
            Pattern.compile("(help|apua|cmds?|commands?|tools?){1}$*", Pattern.CASE_INSENSITIVE);
      
      
      if (quitPattern.matcher(message).find()) {
         message = "Sommoro!\r\n";
         this.send(ByteBuffer.wrap(message.getBytes()));
         this.close();
         return;
      } 
      else
      if (timePattern.matcher(message).find()) {
            Date today = new Date();
            message = today.toString();
      }
      else
      if (greetPattern.matcher(message).find()) {
               message = "Hiyya!";
         }
      else
      if (helpPattern.matcher(message).find()) {
               message = "Commands:  \r\n"
                     + "\t - help \r\n \t - time \r\n \t - quit";
         }
      else {
         echo = true;
         message = "Echo: " + message;
      }
      if (!echo) message += "\r\n";
      
      this.send(ByteBuffer.wrap(message.getBytes()));
   }

   private void close() {
      try {
         channel.close();
         System.out.print("Client Left. ");
      } catch (IOException e) {
         System.out.print("Client failed to quit. ");
         e.printStackTrace();
      }
   }

   private void send(ByteBuffer buffer) {
      try {
         while( buffer.hasRemaining() )
            channel.write( buffer );
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
   
}





Dump your java code here :



Special syntax:
  • To highlight a line (yellow background), prefix it with '@@'
  • To indicate that a line should be removed (red background), prefix it with '-'
  • To indicate that a line should be added (green background), prefix it with '+'
  • To post multiple snippets, seperate them by '~~~~'
  EOF
 

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

The first screenshot will be displayed as a thumbnail.

Nickropheliac (15 views)
2014-08-31 22:59:12

TehJavaDev (23 views)
2014-08-28 18:26:30

CopyableCougar4 (29 views)
2014-08-22 19:31:30

atombrot (41 views)
2014-08-19 09:29:53

Tekkerue (38 views)
2014-08-16 06:45:27

Tekkerue (35 views)
2014-08-16 06:22:17

Tekkerue (24 views)
2014-08-16 06:20:21

Tekkerue (34 views)
2014-08-16 06:12:11

Rayexar (72 views)
2014-08-11 02:49:23

BurntPizza (48 views)
2014-08-09 21:09:32
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!