Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.90 KB | None | 0 0
  1. import java.lang.Object;
  2.  
  3. import java.lang.Character;
  4.  
  5. import java.lang.String;
  6.  
  7. import java.io.*;
  8.  
  9. import java.util.*;
  10.  
  11. import java.net.*;
  12.  
  13. import java.nio.channels.SelectionKey;
  14.  
  15. import java.nio.channels.ServerSocketChannel;
  16.  
  17. import java.nio.channels.SocketChannel;
  18.  
  19. import java.nio.channels.spi.SelectorProvider;
  20.  
  21. import java.nio.channels.Selector;
  22.  
  23. import java.nio.ByteBuffer;
  24.  
  25. import java.lang.Byte;
  26.  
  27. import java.lang.Thread;
  28.  
  29. import java.util.Date;
  30.  
  31. import java.text.SimpleDateFormat;
  32.  
  33.  
  34.  
  35. /**
  36.  
  37.  * @author Sam Jones
  38.  
  39.  * @version 2010.11.06
  40.  
  41.  *
  42.  
  43.  *  This will hold: String characterName, boolean loggedIn, SocketChannel mySocket
  44.  
  45.  *  String[] recentCommands[10], ByteBuffer newLine
  46.  
  47.  *  And whatever else is necessary
  48.  
  49.  *  
  50.  
  51.  *  It will constantly loop, grabbing a byte at a time in to newLine until \n\r (13, 10)
  52.  
  53.  *  is received, where it will execute that command and then push it onto recentCommands[0]
  54.  
  55.  *  
  56.  
  57.  *  If special characters like, Cursor UP, Cursor DOWN, HOME, END, etc are sent. It will send
  58.  
  59.  *  (255) plus whatever telnet command is necessary at that point.
  60.  
  61.  *  
  62.  
  63.  */
  64.  
  65.  
  66.  
  67. public class inputBufferHandler {
  68.  
  69.     private dataPerSocket[] myData = new dataPerSocket[1]; // Increase as necessary
  70.  
  71.    
  72.  
  73.     public inputBufferHandler() throws IOException {
  74.  
  75.         myData[0] = new dataPerSocket();
  76.  
  77.     }
  78.  
  79.     public String getCharacterName(int index) {
  80.  
  81.         if (myData[index].loggedIn) return myData[index].characterName;
  82.  
  83.         return "";
  84.  
  85.     }
  86.  
  87.     public boolean isLoggedIn(int index) {
  88.  
  89.         return myData[index].loggedIn;
  90.  
  91.     }
  92.  
  93.     public boolean isConnected(int index) {
  94.  
  95.         if (myData[index].mySocket != null) return true;
  96.  
  97.         return false;
  98.  
  99.     }
  100.  
  101.     public int getTotal() {
  102.  
  103.         return myData.length;
  104.  
  105.     }
  106.  
  107.     public synchronized void addClient(SelectionKey key) throws IOException {
  108.  
  109.         // Create a reference to our listen socket so we can accept the
  110.  
  111.         // connection to a new selector (this objects selector)
  112.  
  113.         ServerSocketChannel dummyServerReference = (ServerSocketChannel) key.channel();
  114.  
  115.         SocketChannel newClient = dummyServerReference.accept();
  116.  
  117.         newClient.configureBlocking(false);
  118.  
  119.  
  120.  
  121.         // Makes sure the first space gets filled after initialisation
  122.  
  123.         if (isConnected(0)) {
  124.  
  125.             System.out.println("Extending myData to add new client.");
  126.  
  127.             dataPerSocket[] newData = new dataPerSocket[myData.length + 1];
  128.  
  129.             System.arraycopy(myData, 0, newData, 0, myData.length);
  130.  
  131.             newData[myData.length] = new dataPerSocket();
  132.  
  133.             newData[myData.length].beginLife(newClient);
  134.  
  135.             myData = newData;
  136.  
  137.             myData[myData.length - 1].initLogin(newClient);
  138.  
  139.         } else {
  140.  
  141.             System.out.println("Filling first client slot.");
  142.  
  143.             myData[0] = new dataPerSocket();
  144.  
  145.             myData[0].beginLife(newClient);
  146.  
  147.             myData[0].initLogin(newClient);
  148.  
  149.         }
  150.  
  151.     }
  152.  
  153.     public synchronized void delClient(SocketChannel oldClient) throws IOException {
  154.  
  155.         // TODO - this parameter is an example. might pass other stuff
  156.  
  157.     }
  158.  
  159.  
  160.  
  161.  
  162.  
  163.     // Write functions easily accessible from outside this class
  164.  
  165.     public void sendLine(SocketChannel outputSock, String outputLine) throws IOException {
  166.  
  167.         sendMessage(outputSock, outputLine + "\n\r");
  168.  
  169.     }
  170.  
  171.     public void sendMessage(SocketChannel outputSock, String outputLine) throws IOException {
  172.  
  173.         outputSock.write(StringtoBB(outputLine));
  174.  
  175.     }
  176.  
  177.  
  178.  
  179.  
  180.  
  181.     /**
  182.  
  183.      * Converts ByteBuffer to a String and returns it
  184.  
  185.      * Might be redundant after new implementations
  186.  
  187.      */
  188.  
  189.     public String BBtoString(ByteBuffer buf) {
  190.  
  191.         int myCap = buf.capacity() - buf.remaining();
  192.  
  193.         byte[] bytearr = new byte[myCap];
  194.  
  195.         buf.rewind();
  196.  
  197.         for(int i = 0;i < myCap;i++)
  198.  
  199.             bytearr[i] = buf.get(i);
  200.  
  201.         String returnMe = new String(bytearr);
  202.  
  203.         return returnMe;
  204.  
  205.     }
  206.  
  207.     /**
  208.  
  209.      * Converts String to ByteBuffer and returns it
  210.  
  211.      *
  212.  
  213.      * Used with any writing functions to the client
  214.  
  215.      */
  216.  
  217.     public ByteBuffer StringtoBB(String theStr) {
  218.  
  219.         byte[] bytearr = new byte[theStr.length()];
  220.  
  221.         bytearr = theStr.getBytes();
  222.  
  223.         ByteBuffer bbuf = ByteBuffer.allocate(theStr.length());
  224.  
  225.         bbuf = ByteBuffer.wrap(bytearr);
  226.  
  227.         return bbuf;
  228.  
  229.     }
  230.  
  231.  
  232.  
  233.     private class dataPerSocket {
  234.  
  235.         private Thread myLife;
  236.  
  237.         private boolean readMe;
  238.  
  239.         private SocketChannel mySocket;
  240.  
  241.         //      private String[] recentCommands;
  242.  
  243.         //      private ByteBuffer newLine = ByteBuffer.allocate(1024);
  244.  
  245.         private String characterName;
  246.  
  247.         private boolean loggedIn;
  248.  
  249.         private Selector selector; // The selector we'll be monitoring
  250.  
  251.  
  252.  
  253.         public dataPerSocket() throws IOException {
  254.  
  255.             selector = SelectorProvider.provider().openSelector();
  256.  
  257.             readMe = true;
  258.  
  259.             mySocket = null;
  260.  
  261.             //          recentCommands = new String[10];
  262.  
  263.             characterName = "";
  264.  
  265.             loggedIn = false;
  266.  
  267.  
  268.  
  269.         }
  270.  
  271.         public void beginLife(SocketChannel newClient) throws IOException {
  272.  
  273.             // Register it to this objects selector so we can read/write from it in this thread.
  274.  
  275.             newClient.register(selector,  SelectionKey.OP_READ, SelectionKey.OP_WRITE);
  276.  
  277.  
  278.  
  279.             myLife = new Thread(new dataReader());
  280.  
  281.             myLife.start();
  282.  
  283.         }
  284.  
  285.  
  286.  
  287.         public class dataReader implements Runnable {
  288.  
  289.             public void run() {
  290.  
  291.                 String tmpRead = "";
  292.  
  293.                 while (readMe) {
  294.  
  295.                     try {
  296.  
  297.                         // Wait for an event on a registered channel
  298.  
  299.                         selector.select();
  300.  
  301.  
  302.  
  303.                         // Iterate over the selected keys (i.e. OP_ACCEPT - could be OP_READ&OP_WRITE though)
  304.  
  305.                         Iterator selectedKeys = selector.selectedKeys().iterator();
  306.  
  307.                         // Yeah.
  308.  
  309.                         while (selectedKeys.hasNext()) {
  310.  
  311.                             SelectionKey key = (SelectionKey) selectedKeys.next();
  312.  
  313.                             selectedKeys.remove();
  314.  
  315.  
  316.  
  317.                             if (!key.isValid()) {
  318.  
  319.                                 System.out.println("Not valid any more.");
  320.  
  321.                                 readMe = false;
  322.  
  323.                                 break;
  324.  
  325.                             }
  326.  
  327.                             /**
  328.  
  329.                               * Unclean shutdown. Save their information. etc.
  330.  
  331.                               */
  332.  
  333.                             if(!mySocket.socket().isConnected()) {
  334.  
  335.                                 System.out.println(characterName + " quit (non-clean).");
  336.  
  337.                                 // close down socket
  338.  
  339.                                 // close thread
  340.  
  341.                                 // springclean myData
  342.  
  343.                                 // global that they have quit
  344.  
  345.                             }
  346.  
  347.                             if(key.isReadable()) {
  348.  
  349.                                 tmpRead = readLine().replace("\n", "").replace("\r","");
  350.  
  351.                                 if (tmpRead.length() > 0) parse(tmpRead);
  352.  
  353.                                 continue;
  354.  
  355.                             }
  356.  
  357.                         }
  358.  
  359.                     } catch (Exception e) {
  360.  
  361.                         e.printStackTrace();
  362.  
  363.                     }
  364.  
  365.                 }
  366.  
  367.                 System.out.println("dataReader: Finished run().");
  368.  
  369.             }
  370.  
  371.         }
  372.  
  373.  
  374.  
  375.  
  376.  
  377.         private String readLine() throws IOException {
  378.  
  379.             // Buffer.
  380.  
  381.             ByteBuffer buf = ByteBuffer.allocate(1024);
  382.  
  383.  
  384.  
  385.             this.mySocket.read(buf);
  386.  
  387.  
  388.  
  389.             return BBtoString(buf);
  390.  
  391.         }
  392.  
  393.  
  394.  
  395.  
  396.  
  397.         public void initLogin(SocketChannel newClient) throws IOException { // Used by iBH.addClient
  398.  
  399.             this.mySocket = newClient;
  400.  
  401.             Date todaysDate = new java.util.Date();
  402.  
  403.             SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  404.  
  405.             System.out.println("[" + formatter.format(todaysDate) + "] New connection from " + newClient.socket().getInetAddress() + ".");
  406.  
  407.             sendLine(this.mySocket, "*** Welcome to PulseMUD! ***");
  408.  
  409.             sendMessage(this.mySocket, "Enter your username: "); // TODO: Write these functions
  410.  
  411.         }
  412.  
  413.  
  414.  
  415.         // Pushses newComm to the front of the list
  416.  
  417.         //      public void pushCommand(String newComm) {
  418.  
  419.         //          for(int i = 9; i > 0; i--)/
  420.  
  421.         //              recentCommands[i] = recentCommands[i - 1];
  422.  
  423.         //          recentCommands[0] = newComm;
  424.  
  425.         //      }
  426.  
  427.  
  428.  
  429.         public void writeln(String outputLine) throws IOException {
  430.  
  431.             sendMessage(this.mySocket, outputLine + "\n\r");
  432.  
  433.         }
  434.  
  435.  
  436.  
  437.         public void write(String outputLine) throws IOException {
  438.  
  439.             sendLine(this.mySocket, outputLine);
  440.  
  441.         }
  442.  
  443.  
  444.  
  445.         // Used for global commands
  446.  
  447.         public void writeall(String origin, String theMsg) throws IOException {
  448.  
  449.             for (int i  = 0;i < myData.length;i++)
  450.  
  451.                 if (!getCharacterName(i).equals(origin) && isLoggedIn(i))
  452.  
  453.                     myData[i].writeln(theMsg);
  454.  
  455.             return;
  456.  
  457.         }
  458.  
  459.  
  460.  
  461.         //splits a string bases on whitespace and returns the first set of characters before the whitespace
  462.  
  463.         //essentially, the command without arguments, returning it in lowercase --adam
  464.  
  465.         public String stringCommand(String strInput, int x)
  466.  
  467.         {
  468.  
  469.             String strOutput[];
  470.  
  471.             strOutput = strInput.split(" ");
  472.  
  473.             strOutput[x] = strOutput[x].toLowerCase();
  474.  
  475.             return strOutput[x];
  476.  
  477.         }
  478.  
  479.        
  480.  
  481.         public int getStringCommandLength(String strInput)
  482.  
  483.         {
  484.  
  485. //          int length = 0;
  486.  
  487.             String strOutput[];
  488.  
  489.             strOutput = strInput.split(" ");
  490.  
  491.             return strOutput.length;
  492.  
  493.         }
  494.  
  495.        
  496.  
  497.         private void parse(String toParse) throws IOException {
  498.  
  499.             // So I figured that no first command is gonna be more than 10 characters long.
  500.  
  501.             // What I'll do here is read the first 11 characters, searching for a whitespace
  502.  
  503.             // If we get to the 11th character and there's no whitespace or endline, it must be an erroneus commmand
  504.  
  505.             // Otherwise, parse according to that command.
  506.  
  507.  
  508.  
  509.             // Putty was sending a line I didn't recognise, of negative integer bytes. This ignores it.
  510.  
  511.             if (Character.getNumericValue(toParse.charAt(0)) < 0) return;
  512.  
  513.  
  514.  
  515.             // Alternatively, we can do this:
  516.  
  517. //          if (toParse.startsWith("quit")) {
  518.  
  519. //              writeln("This isn't implemented yet!");
  520.  
  521. //              return;
  522.  
  523. //          }
  524.  
  525.             if (stringCommand(toParse, 0).equals("quit")) {
  526.  
  527.                 writeln("This isn't implemented yet!");
  528.  
  529.                 return;
  530.  
  531.             }
  532.  
  533.  
  534.  
  535.             String firstComm = "";
  536.  
  537.             boolean commandOK = false;
  538.  
  539.             int i = 0;
  540.  
  541.             while (i < 11 && i < toParse.length()) {
  542.  
  543.                 if (Character.toString(toParse.charAt(i)).equals(" ")) { commandOK = true; i = 11; break; }
  544.  
  545.                 firstComm += Character.toString(toParse.charAt(i)).toLowerCase();
  546.  
  547.                 i++;
  548.  
  549.             }
  550.  
  551.             if (i == toParse.length() && i < 11) commandOK = true;
  552.  
  553.  
  554.  
  555.  
  556.  
  557.             if (!loggedIn) {
  558.  
  559.                 if (firstComm.matches("[a-zA-Z]{3,10}")) {
  560.  
  561.                     characterName = Character.toString(firstComm.charAt(0)).toUpperCase() + firstComm.substring(1);
  562.  
  563.                     writeln("Welcome to PulseMUD, " + characterName + "!");
  564.  
  565.                     loggedIn = true;
  566.  
  567.                     return;
  568.  
  569.                 } else {
  570.  
  571.                     writeln("Your name must consist of ONLY\n\ralphanumerical characters and must be\n\rbetween 3 and 10 characters long.");
  572.  
  573.                     write("Enter your username: ");
  574.  
  575.                     return;
  576.  
  577.                 }
  578.  
  579.             }
  580.  
  581.  
  582.  
  583.             if (commandOK && firstComm.length() > 0 && firstComm.matches("[a-zA-Z]{0,10}")) { // Begin parsing that beautiful command!
  584.  
  585.                 if (stringCommand(toParse, 1).equals("hello")) { writeln("Hello, " + this.characterName + "!"); return; }
  586.  
  587.                
  588.  
  589.                 if (firstComm.equals("global")) {
  590.  
  591.                     if(getStringCommandLength(toParse) < 1) {
  592.  
  593.                         writeall(characterName, "[" + characterName + "]: " + toParse.substring(7));
  594.  
  595.                         return;
  596.  
  597.                     } else {
  598.  
  599.                         writeln("Include a message!");
  600.  
  601.                     }
  602.  
  603.                 }
  604.  
  605.                
  606.  
  607.  
  608.  
  609.                
  610.  
  611.                 writeln("I don't know command '" + firstComm + "'.");
  612.  
  613.                 return;
  614.  
  615.             } else {
  616.  
  617.                 writeln("Erroneus command.");
  618.  
  619.                 return;
  620.  
  621.             }
  622.  
  623.         }
  624.  
  625.     }
  626.  
  627. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement