Example #1
0
  @Override
  public void run() {
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      PrintWriter out = new PrintWriter(s.getOutputStream());

      String CMD = in.readLine();
      if (CMD.equals("AddMe")) data.addClient(s.getInetAddress().getHostAddress());
      else if (CMD.equals("LISTEN")) {
        if (data.isFree2Listen) {
          synchronized (data) {
            if (data.isFree2Listen) {
              int port = 1291;
              for (port = 1291; port < 65535 && isPortAvailable(port) == false; port++) ;

              out.println("YES " + port);
              data.isFree2Listen = false;
              // TODO LISTEN & pass it to everyone
              new Thread(
                      new Runnable() {
                        @Override
                        public void run() {
                          try {

                            // TODO Auto-generated method stub

                          } catch (Exception e) {
                          }
                        }
                      })
                  .start();
            } else out.println("NO");
          }
        } else out.println("NO");
      } else if (CMD.indexOf("foursquare?access_token=") > -1) {
        String access_token = CMD.substring(CMD.indexOf("foursquare?access_token=") + 24);
        access_token += "\n";
        while ((CMD = in.readLine()) != null) ; // ignore the rest of input
        FileOutputStream file =
            new FileOutputStream(
                Environment.getExternalStorageDirectory().getPath() + "/access_tokens.txt");

        file.write(access_token.getBytes());
        file.close();
        // TODO give the web browser a better response
        String msg =
            "<html><head><title>Done :)</title></head><body>Now,you can close the browser<script>window.close();</script></body></html>";
        out.println(
            "HTTP/1.0 302 Found \r\nContent-Type: text/html; charset=UTF-8 \r\n Content-Length: "
                + msg.getBytes().length
                + "\r\n\r\n"
                + msg);
        out.close();
      }
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }