Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1.  
  2. import java.io.IOException;
  3. import java.nio.ByteBuffer;
  4.  
  5. public class ErlPorts {
  6.  
  7.     private static int readLine(byte[] bytes) {
  8.         try {
  9.             int len;
  10.             if (readExact(bytes, 2) != 2)
  11.                 return -1;
  12.             len = (bytes[0] << 8) | bytes[1];
  13.             return readExact(bytes, len);
  14.         } catch (IOException e) {
  15.             e.printStackTrace();
  16.         }
  17.         return -1;
  18.     }
  19.  
  20.     private static int writeLine(byte[] bytes, int length) {
  21.         byte[] li;
  22.         li = ByteBuffer.allocate(4).putInt((length >> 8) & 0xff).array();
  23.         writeExact(li, 1);
  24.         li = ByteBuffer.allocate(4).putInt(length & 0xff).array();
  25.         writeExact(li, 1);
  26.         return writeExact(bytes, length);
  27.     }
  28.  
  29.     private static int readExact(byte[] bytes, int length) throws IOException{
  30.         int in_count = length;
  31.         int offset = 0;
  32.         do
  33.         {
  34.             int c = System.in.read(bytes, offset, in_count - offset);
  35.             offset += c;
  36.         }
  37.         while (offset < in_count);
  38.         return(in_count);
  39.     }
  40.  
  41.     //TODO:
  42.     private static int writeExact(byte[] bytes, int length) {
  43.         int out_count = length;
  44.         int offset = 0;
  45.         do
  46.         {
  47.             System.out.write (bytes, 0, out_count);
  48.             offset += 2;
  49.         }
  50.         while (offset < out_count);
  51.         return(out_count);
  52.     }
  53.  
  54.     //TODO: foo, bar(nie bardzo wiem co to funkcje mają robić)
  55.  
  56.     private static int foo(int arg) {
  57.         return arg*2;
  58.     }
  59.  
  60.     private static int bar(int arg) {
  61.         return arg/2;
  62.     }
  63.  
  64.     public static void main(String[] args) {
  65.         int fn, arg, res = -1;
  66.         byte[] buf = new byte[100];
  67.  
  68.         while (readLine(buf) > 0) {
  69.             fn = buf[0];
  70.             arg = buf[1];
  71.  
  72.             if (fn == 1) {
  73.                 res = foo(arg);
  74.             } else if (fn == 2) {
  75.                 res = bar(arg);
  76.             }
  77.             buf[0] = ByteBuffer.allocate(4).putInt(res).array()[0];
  78.             writeLine(buf, 1);
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement