Ejemplo n.º 1
0
  public void run() {

    try {
      DataOutputStream out = new DataOutputStream(client.getOutputStream());
      FileInputStream file_in = new FileInputStream(file);
      DataInputStream in = new DataInputStream(file_in);

      byte buffer[] = new byte[512];

      while (in.read(buffer) != -1) {
        System.out.print("\nSending buffer to: " + client_id);
        out.write(buffer, 0, buffer.length);
      }
    } catch (Exception exception) {
      System.out.println("\nException" + exception);
      System.exit(0);
    } finally {
      try {
        client.close();
      } catch (Exception exception) {
        System.out.println("\nException" + exception);
        System.exit(0);
      }
    }
  }
Ejemplo n.º 2
0
  public static int loadURIResource(URI uri, CPU cpu, int addr) {
    int i;

    System.out.println("loadURL: " + uri.toString());

    try {
      DataInputStream s = new DataInputStream(new BufferedInputStream(uri.toURL().openStream()));

      i = 0;
      try {
        while (true) {
          cpu.write8_a32(addr + i, s.readByte());
          i++;
        }
      } catch (EOFException e) {
        // end
      }
    } catch (IOException e) {
      e.printStackTrace(System.err);
      throw new IllegalArgumentException(e);
    }

    System.out.printf("loadURL: '%s' done, %dbytes.\n", uri.toString(), i);

    return i;
  }
Ejemplo n.º 3
0
  public void run() throws IOException {
    ServerSocket server = new ServerSocket(this.portNumber);
    this.socket = server.accept();
    this.socket.setTcpNoDelay(true);
    server.close();

    DataInputStream in = new DataInputStream(this.socket.getInputStream());
    final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
    while (true) {
      final String className = in.readUTF();
      Thread thread =
          new Thread() {
            public void run() {
              try {
                loadAndRun(className);
                out.writeBoolean(true);
                System.err.println(VerifyTests.class.getName());
                System.out.println(VerifyTests.class.getName());
              } catch (Throwable e) {
                e.printStackTrace();
                try {
                  System.err.println(VerifyTests.class.getName());
                  System.out.println(VerifyTests.class.getName());
                  out.writeBoolean(false);
                } catch (IOException e1) {
                  // ignore
                }
              }
            }
          };
      thread.start();
    }
  }
Ejemplo n.º 4
0
  void ReceiveFile() throws Exception {
    String fileName;

    fileName = din.readUTF();

    if (fileName != null && !fileName.equals("NOFILE")) {
      System.out.println("Receiving File");
      File f =
          new File(
              System.getProperty("user.home")
                  + "/Desktop"
                  + "/"
                  + fileName.substring(fileName.lastIndexOf("/") + 1));
      System.out.println(f.toString());
      f.createNewFile();
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      System.out.println("Received File : " + fileName);
      fout.close();
    } else {
    }
  }
Ejemplo n.º 5
0
  public static void main(String[] args) {
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);
    DataInputStream in;
    DataOutputStream out;
    Socket client;

    try {
      // create connection to server
      client = new Socket(serverName, port);

      // send the string  "LISTENER" to server first!!
      out = new DataOutputStream(client.getOutputStream());
      out.writeUTF("LISTENER");

      // continuously receive messages from server
      // using stdout to print out messages Received
      // do not close the connection- keep listening to further messages from the server.
      in = new DataInputStream(client.getInputStream());
      while (true) {
        System.out.println(in.readUTF());
      }
    } catch (UnknownHostException e) {

    } catch (IOException e) {

    }
  }
  public HTTPSConnectSocket(String host, int port, String urlString) throws IOException {

    URL url = null;
    try {
      url = new URL(urlString);
    } catch (MalformedURLException me) {
      System.out.println("Malformed url");
      System.exit(1);
    }

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ssl = (SSLSocket) ssf.createSocket(host, port);
    ssl.startHandshake();

    // Send the CONNECT request
    ssl.getOutputStream().write(("CONNECT " + url.getFile() + " HTTP/1.0\r\n\r\n").getBytes());

    // Read the first line of the response
    DataInputStream is = new DataInputStream(ssl.getInputStream());
    String str = is.readLine();

    // Check the HTTP error code -- it should be "200" on success
    if (!str.startsWith("HTTP/1.1 200 ")) {
      if (str.startsWith("HTTP/1.1 ")) str = str.substring(9);
      throw new IOException("Proxy reports \"" + str + "\"");
    }

    // Success -- skip remaining HTTP headers
    do {
      str = is.readLine();
    } while (str.length() != 0);
  }
Ejemplo n.º 7
0
    public void run() {
      try {
        while (true) {
          StringBuffer sb = new StringBuffer();
          DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()));
          String inputLine = "";
          int i;
          // System.out.println("server prepare accept msg");
          while ((i = is.read()) != 59) {

            if (i == -1) {

              continue;
            }
            sb.append((char) i);
          }
          if (sb.toString().indexOf("NETTST") == -1) {
            System.out.println("服务器收到信息为" + sb.toString());
          }
          System.out.println("服务器收到信息为" + sb.toString());
          // System.out.println("server has accept msg");
          this.sleep(2000);
          // is.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Ejemplo n.º 8
0
  /**
   * Open FBS file identified by {@link #fbsURL}. The stream is positioned at the entry point
   * described by <code>entryPoint</code>.
   *
   * @param entryPoint entry point information.
   * @return a newly created FBS input stream on success, <code>null</code> if any error occured and
   *     the FBS stream is not opened.
   * @throws java.io.IOException if an I/O exception occurs.
   */
  private FbsInputStream openFbsFile(FbsEntryPoint entry) throws IOException {

    System.err.println("Entering FBS at " + entry.timestamp + " ms");

    // Make sure the protocol is HTTP.
    if (!fbkURL.getProtocol().equalsIgnoreCase("http")
        || !fbsURL.getProtocol().equalsIgnoreCase("http")) {
      System.err.println("Indexed access requires HTTP protocol in URLs");
      return null;
    }

    // Seek to the keyframe.
    InputStream is = openHttpByteRange(fbkURL, entry.key_fpos, entry.key_size);
    if (is == null) {
      return null;
    }

    // Load keyframe data from the .fbk file, prepend RFB initialization data.
    DataInputStream data = new DataInputStream(is);
    byte[] keyData = new byte[rfbInitData.length + (int) entry.key_size];
    System.arraycopy(rfbInitData, 0, keyData, 0, rfbInitData.length);
    data.readFully(keyData, rfbInitData.length, (int) entry.key_size);
    data.close();

    // Open the FBS stream.
    is = openHttpByteRange(fbsURL, entry.fbs_fpos, -1);
    if (is == null) {
      return null;
    }
    return new FbsInputStream(is, entry.timestamp, keyData, entry.fbs_skip);
  }
Ejemplo n.º 9
0
 public void run() {
   try {
     boolean connected = true;
     System.out.println("a client has connected!");
     dis = new DataInputStream(s.getInputStream());
     dos = new DataOutputStream(s.getOutputStream());
     while (connected) {
       int cid = clients.indexOf(this) + 1;
       try {
         String str = dis.readUTF();
         System.out.println(str);
         for (int i = 0; i < clients.size(); i++) {
           clients.get(i).dos.writeUTF("Client" + cid + ":" + str);
         }
       } catch (IOException e) {
         connected = false;
       }
     }
     dis.close();
     dos.close();
     s.close();
     clients.remove(this);
     System.out.println("a client is qiut!");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 10
0
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
  public static void send_JPIPstream(
      byte[] jpipstream, String j2kfilename, String tid, String cid) {
    try {
      Socket imgdecSocket = new Socket("localhost", 50000);
      DataOutputStream os = new DataOutputStream(imgdecSocket.getOutputStream());
      DataInputStream is = new DataInputStream(imgdecSocket.getInputStream());
      int length = 0;

      if (jpipstream != null) length = jpipstream.length;

      System.err.println("Sending " + length + "Data Bytes to decodingServer");

      os.writeBytes("JPIP-stream\n");
      os.writeBytes("version 1.2\n");
      os.writeBytes(j2kfilename + "\n");
      if (tid == null) os.writeBytes("0\n");
      else os.writeBytes(tid + "\n");
      if (cid == null) os.writeBytes("0\n");
      else os.writeBytes(cid + "\n");
      os.writeBytes(length + "\n");
      os.write(jpipstream, 0, length);

      byte signal = is.readByte();

      if (signal == 0) System.err.println("    failed");
    } catch (UnknownHostException e) {
      System.err.println("Trying to connect to unknown host: " + e);
    } catch (IOException e) {
      System.err.println("IOException: " + e);
    }
  }
Ejemplo n.º 12
0
  int[] readPlanarRGB(InputStream in) throws IOException {
    if (fi.compression > FileInfo.COMPRESSION_NONE) return readCompressedPlanarRGBImage(in);
    DataInputStream dis = new DataInputStream(in);
    int planeSize = nPixels; // 1/3 image size
    byte[] buffer = new byte[planeSize];
    int[] pixels = new int[nPixels];
    int r, g, b;

    startTime = 0L;
    showProgress(10, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      r = buffer[i] & 0xff;
      pixels[i] = 0xff000000 | (r << 16);
    }

    showProgress(40, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      g = buffer[i] & 0xff;
      pixels[i] |= g << 8;
    }

    showProgress(70, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      b = buffer[i] & 0xff;
      pixels[i] |= b;
    }

    showProgress(90, 100);
    return pixels;
  }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
Ejemplo n.º 14
0
  private static void getMedicineList(Socket socket) {
    int medicineID;
    String medicineName;
    String medicineUnit;
    double price;

    try {
      OutputStream output = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(output);
      InputStream input = socket.getInputStream();
      DataInputStream dis = new DataInputStream(input);

      dos.writeInt(8);

      int numberOfMedicine = dis.readInt();

      for (int i = 0; i < numberOfMedicine; i++) {
        medicineID = dis.readInt();
        medicineName = dis.readUTF();
        medicineUnit = dis.readUTF();
        price = dis.readDouble();

        medicineList.add(new Medicine(medicineID, medicineName, medicineUnit, price));
      }

    } catch (IOException e) {
      System.out.println("Cannot get IO streams.");
    }
  }
Ejemplo n.º 15
0
 /**
  * Se encarga de leer los String que provienen desde el cliene y redirecciona de acuerdo a las
  * acciones solicitadas
  */
 protected void readC(Socket socket) {
   try {
     InputStream entra = socket.getInputStream();
     DataInputStream flujo = new DataInputStream(entra);
     String jsondata = flujo.readUTF();
   } catch (Exception e) {
     System.out.println(e.getMessage());
   }
 }
Ejemplo n.º 16
0
  private int Load_Nodes(DataInputStream inStream) {
    // need to open file and load data
    int node_id;
    int x_cor;
    int y_cor;
    // int n_nodes, n_edges, node_cnt, arrow_status;
    Node n;
    String line;
    String item1, item2, item3, item4;

    node_id = 0;
    x_cor = 0;
    y_cor = 0;
    // n_nodes = 0;
    // n_edges = 0;
    // arrow_status = -1;

    try {

      if ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        n_nodes = Integer.parseInt(item1);
        item2 = Data.nextToken();
        n_edges = Integer.parseInt(item2);
        item3 = Data.nextToken();
        arrow_status = Integer.parseInt(item3);
        // item4 = Data.nextToken();
        // type = Integer.parseInt( item4 );
        // graph = new GraphClass( n_nodes, n_edges, arrow_status );
        nodes = new Node[n_nodes];
        edges = new Edge[n_edges];

        // ???

        while ((this.Node_Cnt() < n_nodes) && ((line = inStream.readLine()) != null)) {
          Data = new StringTokenizer(line, " ");
          item1 = Data.nextToken();
          item2 = Data.nextToken();
          item3 = Data.nextToken();
          node_id = Integer.parseInt(item1);
          x_cor = Integer.parseInt(item2);
          y_cor = Integer.parseInt(item3);
          n = new Node(node_id, x_cor, y_cor);
          this.Add_Node(n);
        }
        if (n_nodes != 0) {
          source_node = nodes[0];
        }
      }
    } catch (IOException e) {
      System.err.println("error in file" + e.toString());
      System.exit(1);
    }
    return this.Node_Cnt();
  }
Ejemplo n.º 17
0
  public static void start(int serverPort) {
    String address =
        "127.0.0.1"; // это IP-адрес компьютера, где исполняется наша серверная программа.
    // Здесь указан адрес того самого компьютера где будет исполняться и клиент.
    try {
      InetAddress ipAddress =
          InetAddress.getByName(
              address); // создаем объект который отображает вышеописанный IP-адрес.
      System.out.println(
          "Any of you heard of a socket with IP address "
              + address
              + " and port "
              + serverPort
              + "?");
      Socket socket =
          new Socket(ipAddress, serverPort); // создаем сокет используя IP-адрес и порт сервера.
      System.out.println("Yes! I just got hold of the program.");

      // Берем входной и выходной потоки сокета, теперь можем получать и отсылать данные клиентом.
      InputStream sin = socket.getInputStream();
      OutputStream sout = socket.getOutputStream();

      // Конвертируем потоки в другой тип, чтоб легче обрабатывать текстовые сообщения.
      DataInputStream in = new DataInputStream(sin);
      DataOutputStream out = new DataOutputStream(sout);

      // Создаем поток для чтения с клавиатуры.
      BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
      String line = null;
      System.out.println(
          "Type in something and press enter. Will send it to the server and tell ya what it thinks.");
      System.out.println();

      while (true) {
        line = keyboard.readLine(); // ждем пока пользователь введет что-то и нажмет кнопку Enter.
        if (line == null) {
          continue;
        }
        System.out.println("Sending this line to the server...");
        out.writeUTF(line); // отсылаем введенную строку текста серверу.
        out.flush(); // заставляем поток закончить передачу данных.
        boolean isTransactionSucceed = in.readBoolean(); // ждем пока сервер отошлет ответ.
        if (isTransactionSucceed) {
          System.out.println("Success!");
        } else {
          System.out.println("Failed");
        }
        System.out.println();
      }
    } catch (SocketException x) {
      System.out.println("Server doesn't response anymore");
      System.out.println();
    } catch (Exception x) {
      x.printStackTrace();
    }
  }
Ejemplo n.º 18
0
 @SuppressWarnings("deprecation")
 private static String ReadInput() throws Exception {
   String zipCode;
   DataInputStream inData = new DataInputStream(System.in);
   zipCode = inData.readLine();
   int zip = Integer.parseInt(zipCode);
   if (zip < 501 || zip > 99950) throw new Exception("zip code not found");
   if (zipCode.length() != 5) throw new NumberFormatException();
   return zipCode;
 }
Ejemplo n.º 19
0
  /**
   * Connect to searchd server and update given attributes on given documents in given indexes.
   * Sample code that will set group_id=123 where id=1 and group_id=456 where id=3:
   *
   * <pre>
   * String[] attrs = new String[1];
   *
   * attrs[0] = "group_id";
   * long[][] values = new long[2][2];
   *
   * values[0] = new long[2]; values[0][0] = 1; values[0][1] = 123;
   * values[1] = new long[2]; values[1][0] = 3; values[1][1] = 456;
   *
   * int res = cl.UpdateAttributes ( "test1", attrs, values );
   * </pre>
   *
   * @param index index name(s) to update; might be distributed
   * @param attrs array with the names of the attributes to update
   * @param values array of updates; each long[] entry must contains document ID in the first
   *     element, and all new attribute values in the following ones
   * @param ignorenonexistent the flag whether to silently ignore non existent columns up update
   *     request
   * @return -1 on failure, amount of actually found and updated documents (might be 0) on success
   * @throws SphinxException on invalid parameters
   */
  public int UpdateAttributes(
      String index, String[] attrs, long[][] values, boolean ignorenonexistent)
      throws SphinxException {
    /* check args */
    myAssert(index != null && index.length() > 0, "no index name provided");
    myAssert(attrs != null && attrs.length > 0, "no attribute names provided");
    myAssert(values != null && values.length > 0, "no update entries provided");
    for (int i = 0; i < values.length; i++) {
      myAssert(values[i] != null, "update entry #" + i + " is null");
      myAssert(values[i].length == 1 + attrs.length, "update entry #" + i + " has wrong length");
    }

    /* build and send request */
    ByteArrayOutputStream reqBuf = new ByteArrayOutputStream();
    DataOutputStream req = new DataOutputStream(reqBuf);
    try {
      writeNetUTF8(req, index);

      req.writeInt(attrs.length);
      req.writeInt(ignorenonexistent ? 1 : 0);
      for (int i = 0; i < attrs.length; i++) {
        writeNetUTF8(req, attrs[i]);
        req.writeInt(0); // not MVA attr
      }

      req.writeInt(values.length);
      for (int i = 0; i < values.length; i++) {
        req.writeLong(values[i][0]); /* send docid as 64bit value */
        for (int j = 1; j < values[i].length; j++)
          req.writeInt(
              (int)
                  values[i][
                      j]); /* send values as 32bit values; FIXME! what happens when they are over 2^31? */
      }

      req.flush();

    } catch (Exception e) {
      _error = "internal error: failed to build request: " + e;
      return -1;
    }

    /* get and parse response */
    DataInputStream in = _DoRequest(SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, reqBuf);
    if (in == null) return -1;

    try {
      return in.readInt();
    } catch (Exception e) {
      _error = "incomplete reply";
      return -1;
    }
  }
  public void registrarUsuario() {
    String dato = "";
    JSONParser parser = new JSONParser();
    try {
      while (true) {
        dato = dis.readUTF();
        String usuario = "";
        String contraseña = "";
        String contra = "";
        if (dato.equals("Usuario")) {
          while (true) {
            usuario = dis.readUTF();
            if (usuario != null) {
              JSONObject user = new JSONObject();
              user.put(usuario, null);
              FileWriter escribir = new FileWriter("texto.txt");
              BufferedWriter bw = new BufferedWriter(escribir);
              PrintWriter pw = new PrintWriter(bw);
              pw.write(user.toJSONString());
              pw.close();
              bw.close();
              while (true) {
                contra = dis.readUTF();
                if (contra.equals("Contraseña")) {
                  while (true) {
                    contraseña = dis.readUTF();
                    if (contraseña != null) {
                      Object obj = parser.parse(new FileReader("texto.txt"));
                      JSONObject asignaPass = (JSONObject) obj;
                      asignaPass.put(usuario, contra);
                      FileWriter escribir2 = new FileWriter("texto.txt");
                      BufferedWriter bw2 = new BufferedWriter(escribir2);
                      PrintWriter pw2 = new PrintWriter(bw2);
                      pw2.write(asignaPass.toJSONString());
                      bw2.newLine();
                      pw2.close();
                      bw2.close();
                      break;
                    }
                  }
                  break;
                }
              }
              break;
            }
          }
          break;
        }
      }
    } catch (Exception e) {

    }
  }
 public int[] readProgress() {
   int progress[] = new int[2];
   try {
     DataInputStream in =
         new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file)));
     progress[0] = in.readInt();
     progress[1] = in.readInt();
     in.close();
   } catch (FileNotFoundException e) {
     Log.e(TAG, "readProgress file not found.");
   } catch (IOException e) {
     Log.e(TAG, e.getMessage());
   }
   return progress;
 }
Ejemplo n.º 22
0
 protected void processOtherMsg(int msgsize, int msgtype, DataInputStream dIn)
     throws SocketException, IOException, java.lang.NullPointerException {
   dIn.skipBytes(msgsize - 2); // need to just skip this message because we don't recognize it
   ExpCoordinator.printer.print(
       new String("NCCPConnection.processOtherMsg skipping message " + msgsize + " " + msgtype));
   ExpCoordinator.printer.printHistory();
 }
Ejemplo n.º 23
0
  private int Load_Edges(DataInputStream inStream, int num) {
    String line;
    String item1, item2, item3;
    int source_node;
    int dest_node;
    int value;
    int n_nodes, edge_cnt;
    // Node nodes_array[] = new Node[num]; // Wil
    Edge edge;
    n_nodes = num;
    Node nodes_array[];
    nodes_array = new Node[n_nodes];
    nodes_array = this.Node_Array(); // Wil
    edge_cnt = 0;

    try {
      while ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        item2 = Data.nextToken();
        item3 = Data.nextToken();
        source_node = Integer.parseInt(item1);
        dest_node = Integer.parseInt(item2);
        value = Integer.parseInt(item3);
        edge = new Edge(nodes_array[source_node - 1], nodes_array[dest_node - 1], value);
        this.Add_Edge(edge);
        edge_cnt++;
      }
      // inFile.close();
    } catch (IOException e) {
      System.err.println("Error in accessing URL: " + e.toString());
      System.exit(1);
    }
    return edge_cnt;
  }
Ejemplo n.º 24
0
 public void run() {
   while (flag) {
     try {
       String msg = din.readUTF().trim();
       if (msg.startsWith("<#NICK_NAME#>")) {
         this.nick_name(msg);
       } else if (msg.startsWith("<#CLIENT_LEAVE#>")) {
         this.client_leave(msg);
       } else if (msg.startsWith("<#CHALLENGE#>")) {
         this.challenge(msg);
       } else if (msg.startsWith("<#AGREE#>")) {
         this.agree(msg);
       } else if (msg.startsWith("<#DISAGREE#>")) {
         this.disagree(msg);
       } else if (msg.startsWith("<#BUSY#>")) {
         this.busy(msg);
       } else if (msg.startsWith("<#MOVE#>")) {
         this.move(msg);
       } else if (msg.startsWith("<#SURRENDER#>")) {
         this.surrender(msg);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 25
0
 public void close() {
   try {
     if (streamIn != null) streamIn.close();
   } catch (IOException ioe) {
     System.out.println("Error closing input stream: " + ioe);
   }
 }
  /** Method declaration */
  public void run() {

    Channel c = init();

    if (c != null) {
      try {
        while (true) {
          String sql = mInput.readUTF();

          mServer.trace(mThread + ":" + sql);

          if (sql == null) {
            break;
          }

          write(mDatabase.execute(sql, c).getBytes());
        }
      } catch (Exception e) {
      }
    }

    try {
      mSocket.close();
    } catch (IOException e) {
    }

    if (mDatabase.isShutdown()) {
      System.out.println("The database is shutdown");
      System.exit(0);
    }
  }
Ejemplo n.º 27
0
  public static void main(String[] ar) {

    int port = 6000;
    Date sysDate = new Date();
    String sysDateStr2;
    sysDateStr2 = new SimpleDateFormat("yyyy-MM-dd").format(sysDate).toString();
    try {
      ServerSocket ss = new ServerSocket(port);
      System.out.println("Waiting for a client to connect...");
      System.out.println("client connected");
      System.out.println();

      String msg = null;
      String IP, Date;
      float upload, download;
      Socket socket = ss.accept();
      InputStream sin = socket.getInputStream();
      OutputStream sout = socket.getOutputStream();
      DataInputStream in = new DataInputStream(sin);
      DataOutputStream out = new DataOutputStream(sout);
      while (true) {

        msg = in.readUTF(); // wait for the client to send a line of text.
        System.out.println("IP address:" + msg);
        IP = msg;
        msg = in.readUTF();
        System.out.println("Upload:" + msg);

        upload = Float.parseFloat(msg);
        msg = in.readUTF();
        System.out.println("Download:" + msg);
        download = Float.parseFloat(msg);
        System.out.println("Date:" + sysDateStr2);
        Date = sysDateStr2;
        recieveTrafficRates(IP, upload, download);
        out.writeUTF(msg);
        // in.read(b);
        out.flush();
        System.out.println("Waiting for the next line...");
        System.out.println();
      }

    } catch (Exception x) {

      x.printStackTrace();
    }
  }
Ejemplo n.º 28
0
 // 读取保存的下载信息(文件指针位置)
 private void read_nPos() {
   try {
     DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));
     int nCount = input.readInt();
     nStartPos = new long[nCount];
     nEndPos = new long[nCount];
     for (int i = 0; i < nStartPos.length; i++) {
       nStartPos[i] = input.readLong();
       nEndPos[i] = input.readLong();
     }
     input.close();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 29
0
 public String getMessage() {
   try {
     return dataIn.readUTF();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return "";
 }
Ejemplo n.º 30
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here

    long lNumOfLines = 0;
    List list1 = new ArrayList();

    try {
      FileInputStream fstream = new FileInputStream("n:\\myphd\\dataset\\gps.csv");
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      // Read File Line By Line
      while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        lNumOfLines++;
        list1.add(strLine.trim());
      }
      // Close the input stream
      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    long lTotal = 1000000;
    long numberOfLines = 0;
    long lStep = lTotal / lNumOfLines;
    System.out.println("lTotal:" + lTotal + " numberOfLines:" + numberOfLines + "lStep:" + lStep);
    float fSpeed = 100;
    float newfSpeed = 0;
    for (int iNum = 0; iNum < lStep; iNum++) {
      Random randomGenerator = new Random();
      int randomInt = randomGenerator.nextInt(1000);
      float f = (float) randomInt / 10000.0f;
      System.out.println("Random Int:" + randomInt + " f:" + f);
      if ((randomInt % 2) == 0) {
        newfSpeed = fSpeed + fSpeed * f;
        System.out.println("Even");
      } else {
        newfSpeed = fSpeed - fSpeed * f;
        System.out.println("odd");
      }
      // InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
      System.out.println("generated speed:" + newfSpeed);
    }
  }