public void connect(GUIClient GUI) throws IOException {

    try {
      connectSocket = new Socket(ServerIp, ServerPort);
      out = new PrintWriter(connectSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(connectSocket.getInputStream()));
    } catch (UnknownHostException e) {
      System.err.println("Cannot Connect to server");
      // System.exit(1);
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for " + "the connection to: " + ServerIp.toString());
      // System.exit(1);
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    String clientInput = GUI.getJTareaOut().getText();

    while ((clientInput = stdIn.readLine()) != null) {
      out.println(clientInput);
      System.out.println("Writing: " + in.readLine());
    }

    out.close();
    in.close();
    stdIn.close();
    connectSocket.close();
  }
Ejemplo n.º 2
0
Archivo: F.java Proyecto: ballon/hz
  public static void main(String[] args) throws IOException, InterruptedException {
    for (int iter = 1; iter <= 1000; ++iter) {
      System.out.println("HELLO");

      // ask for a value
      Socket s1 = new Socket("127.0.0.1", 12345);
      PrintWriter out = new PrintWriter(s1.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(s1.getInputStream()));
      out.println(-1);
      String response = in.readLine();
      s1.close();
      out.close();
      in.close();

      // increase by 1
      int val = Integer.parseInt(response);
      val++;

      // set value
      Socket s2 = new Socket("127.0.0.1", 12345);
      out = new PrintWriter(s2.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(s2.getInputStream()));
      out.println(val);
      s2.close();
      out.close();
      in.close();
    }
  }
Ejemplo n.º 3
0
  public static void main(String[] args) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    BufferedReader userInputStream = null;
    String IP = "127.0.0.1";
    final int PORT_NUM = 4444;
    try {
      socket = new Socket(IP, PORT_NUM);
      out = new PrintWriter(socket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
      System.out.println("Unknown host:" + IP + " at port: " + PORT_NUM);
      e.printStackTrace();
      System.exit(0);
    } catch (IOException e) {
      System.out.println("Cannot connect to server...");
      e.printStackTrace();
      System.exit(0);
    }
    String userInput, fromServer;
    try {
      userInputStream = new BufferedReader(new InputStreamReader(System.in));
      while ((fromServer = in.readLine()) != null) {
        System.out.println("Server: " + fromServer);
        if (fromServer.equals(":q")) break;

        userInput = userInputStream.readLine();
        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        if (userInput != null) {
          out.println(userInput + " (sent at " + (sdf.format(cal.getTime())) + ")");
        }
      }
    } catch (IOException e) {
      System.out.println("Could not access data from client printstream...");
      e.printStackTrace();
      System.exit(0);
    }
    try {
      out.close();
      in.close();
      userInputStream.close();
      socket.close();
      System.out.println("I love you, bye.");
      System.out.println("Terminating client...");
    } catch (IOException e) {
      System.out.println("Socket and stream closing error...");
      e.printStackTrace();
      System.exit(0);
    }
  }
Ejemplo n.º 4
0
  public static void main(String[] args) {
    String ipv4;
    try {
      System.out.println("Stablishing the server socket...");
      ServerSocket srvSock = new ServerSocket(4201);
      System.out.println(
          "Server socket stablished to "
              + srvSock.getInetAddress().getHostName()
              + " at port number "
              + srvSock.getLocalPort()
              + ".\n");

      try {
        Socket comSock = srvSock.accept();
        System.out.println(
            "New connection stablished with "
                + comSock.getInetAddress().getHostName()
                + " (port "
                + comSock.getPort()
                + "), trying to communicate...");
        // DO STUFF
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream()));
          ipv4 = br.readLine();
          br.close();
          comSock.close();
          srvSock.close();
          Socket sock = new Socket(ipv4, 4202);
          BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          System.out.println(br2.readLine());
          br2.close();
          sock.close();
          // System.out.println(ipv4);
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Connection failed. Try again later.");
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Problem with client.\n");
      }

    } catch (Exception e) {
      System.out.println("Failed to create server socket:");
      e.printStackTrace();
    }
  }
Ejemplo n.º 5
0
    private String getAddressXY(String x, String y) {
      try {
        StringBuilder text = new StringBuilder();

        String url = properties.getProperty("geocoderUrl");
        String param1 = properties.getProperty("geocoderUrlParam1");
        String param2 = properties.getProperty("geocoderUrlParam2");
        url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y;

        URL page = new URL(url);
        HttpURLConnection urlConn = (HttpURLConnection) page.openConnection();
        urlConn.connect();
        InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line = buff.readLine();

        while (line != null) {
          text.append(line);
          line = buff.readLine();
        }

        String result = text.toString();
        buff.close();
        in.close();

        return result;

      } catch (MalformedURLException e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      } catch (Exception e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      }
    }
Ejemplo n.º 6
0
  public static void main(String a[]) throws Exception {

    boolean bool = false;

    try {
      InputStreamReader in = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(in);

      do {
        Socket clientSocket = new Socket("localhost", 6789);
        TCPClient client = new TCPClient(clientSocket);
        client.talkOnSocket();

        System.out.println("Do you want tranfer another file : Y/N");
        String choise = br.readLine().trim();
        if (choise.equalsIgnoreCase("y")) {
          bool = true;
        } else if (choise.equalsIgnoreCase("n")) {
          bool = false;
        } else {
          bool = false;
          System.out.println("Invalid entry. Clsoing.");
        }
      } while (bool);
      in.close();
      br.close();

    } catch (Exception e) {
      System.out.println("Server might not be up and running....");
      System.exit(0);
    }
  }
Ejemplo n.º 7
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Ejemplo n.º 8
0
  public Server() {
    try {
      ServerSocket ss = new ServerSocket(SERVER_PORT);

      Socket s = ss.accept();

      InputStream is = s.getInputStream();
      OutputStream out = s.getOutputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String sss = br.readLine();
      System.out.println(sss);

      PrintWriter pw = new PrintWriter(out);
      pw.print("hello,我是服务器。");

      pw.close();
      br.close();
      isr.close();
      out.close();
      is.close();
      s.close();
      ss.close();
    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (IOException oe) {
      oe.printStackTrace();
    }
  }
  @Override
  public void run() {
    // System.out.println ("New Communication Thread Started");

    try {
      BufferedReader in;
      // OUTPUT STREAM
      try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        // READ NUMBER OF FORTUNE COOKIES CLIENT WANTS
        while ((inputLine = in.readLine()) != null) {
          // System.out.println("Hello");
          if (inputLine.equals("Bye.")) break;
          int number = Integer.parseInt(inputLine);
          System.out.println("Server: " + inputLine);
          // SENDS RANDOMLY GENERATED COOKIES
          out.println(new FortuneCookies().getCookies(number));
        }
      }
      // CLIENT CLOSE
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
Ejemplo n.º 10
0
  /**
   * A asynchronous method for reading the content of the file.
   *
   * @return the content of the file, or an empty string when there's nothing in the file.
   */
  public String getFileContent() {
    InputStream stream = getClass().getResourceAsStream(COOKIE);
    // The cookie file doesn't exist
    if (stream == null) return "";

    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

    String line = null;
    try {
      // only one line is needed
      line = reader.readLine();
      reader.close();
    } catch (IOException e) {
      return "";
    }

    // Line can't continue to be processed.
    if (line == null) return "";

    // hasn't got an updateID yet.
    if (updateID == null) {
      setUpdateID(line);
      return line;
    } else {
      // The updateID hasn't been updated yet.
      if (updateID.equals(extractUpdateID(line))) return "";
      // There is a new updateID in the file, so update it.
      else {
        setUpdateID(line);
        return line;
      }
    }
  }
Ejemplo n.º 11
0
  private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
Ejemplo n.º 12
0
  public void doTest(String path, int expectedStatus) throws Exception {

    InputStream is = null;
    BufferedReader input = null;

    try {
      URL url = new URL("http://" + host + ":" + port + contextRoot + "/" + path);
      System.out.println("Connecting to: " + url.toString());

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.connect();

      int responseCode = conn.getResponseCode();
      if (responseCode != expectedStatus) {
        throw new Exception("Unexpected return code: " + responseCode);
      }

      if (responseCode == HttpURLConnection.HTTP_OK) {
        is = conn.getInputStream();
        input = new BufferedReader(new InputStreamReader(is));
        String response = input.readLine();
      }
    } finally {
      try {
        if (is != null) is.close();
      } catch (IOException ex) {
      }
      try {
        if (input != null) input.close();
      } catch (IOException ex) {
      }
    }
  }
  /** Destroys the server stored list. */
  @Override
  public void destroy() {
    stopped = true;

    try {
      if (connection != null) {
        connection.shutdownInput();
        connection.close();
        connection = null;
      }
    } catch (IOException e) {
    }

    try {
      if (connectionReader != null) {
        connectionReader.close();
        connectionReader = null;
      }
    } catch (IOException ex) {
    }

    if (connectionWriter != null) {
      connectionWriter.close();
      connectionWriter = null;
    }
  }
Ejemplo n.º 14
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Ejemplo n.º 15
0
  private readURL() {

    init();

    //		create an URL instance
    try {
      url = new URL(webpage);

    } catch (MalformedURLException except1) {
      System.out.println("MALFORMED URL ERROR\nREADY.");
    }
    ;

    //		create "read"-stream from URL
    try {
      in = new BufferedReader(new InputStreamReader(url.openStream()));

    } catch (IOException except2) {
      System.out.println("IOEXCEPTION ERROR !\nREADY.");
    }
    ;

    //		read the stream
    String inputLine;
    try {
      while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
      in.close();

    } catch (IOException except3) {
      System.out.println("IOEXCEPTION ERROR AGAIN !\nREADY.");
    }
    ;
  }
Ejemplo n.º 16
0
  public void kill() {

    try {
      client.close();
      toUser.close();
      fromUser.close();
      altSockIn.close();
      inFromServer.close();
      toServer.close();
      altSock.close();
      userSock.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 17
0
  /**
   * create a Bufferedreader that read from the open url The parameter of the search term research
   * can be setup using the various command
   */
  private boolean download() {
    buffer = new StringBuilder();
    // --1. Encode url?

    // --2. Do the work
    try {
      url = new URL(composite_url);
      // Config.log("ESearch for: "+search_term);
    } catch (MalformedURLException e) {
      Config.log("Error: URL is not good.\n" + composite_url);
    }
    try {
      if (in_connection_open) in_connection.close();

      in_connection = new BufferedReader(new InputStreamReader(url.openStream()));
      if (in_connection != null) in_connection_open = true;
      String inputLine = "";
      if (isOutputToDisk()) output = new PrintWriter(new FileWriter(new File(filename)));
      while ((inputLine = in_connection.readLine()) != null) {
        if (!this.isOutputToDisk()) {
          buffer.append(inputLine + "\n");
        } else {
          output.println(inputLine);
        }
      }
      if (isOutputToDisk()) {
        output.flush();
        output.close();
      }
    } catch (IOException e) {
      Config.log("Unable to download from..." + composite_url);
      return false;
    }
    return true;
  }
  /**
   * Load string map from a URL.
   *
   * @param mapURL URL for map file.
   * @param separator Field separator.
   * @param qualifier Quote character.
   * @param encoding Character encoding for the file.
   * @throws FileNotFoundException If input file does not exist.
   * @throws IOException If input file cannot be opened.
   * @return Map with values read from file.
   */
  public static Map<String, String> loadMap(
      URL mapURL, String separator, String qualifier, String encoding)
      throws IOException, FileNotFoundException {
    Map<String, String> map = MapFactory.createNewMap();

    if (mapURL != null) {
      BufferedReader bufferedReader =
          new BufferedReader(new UnicodeReader(mapURL.openStream(), encoding));

      String inputLine = bufferedReader.readLine();
      String[] tokens;

      while (inputLine != null) {
        tokens = inputLine.split(separator);

        if (tokens.length > 1) {
          map.put(tokens[0], tokens[1]);
        }

        inputLine = bufferedReader.readLine();
      }

      bufferedReader.close();
    }

    return map;
  }
  private String handleConnection() {
    String content = null;
    try {
      PrintWriter streamWriter = new PrintWriter(connection.getOutputStream());
      BufferedReader streamReader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()));

      content = streamReader.readLine();

      //            System.out.println(content);
      log.debug("receiveing begin............\r\n");
      log.debug(content);
      log.debug("receiveing end........");
      streamWriter.println(content + "\r\n");
      //            streamWriter.println("hello\r\n");
      streamWriter.flush();

      streamReader.close();
      streamWriter.close();
      //            connection.close();
      return content;
    } catch (FileNotFoundException e) {
      //            System.out.println("Could not find requested file on the server.");
      log.error("Could not find requested file on the server.");
      return content;
    } catch (IOException e) {
      //            System.out.println("Error handling a client: " + e);
      log.error("Error handling a client: " + e);
      return content;
    }
  }
Ejemplo n.º 20
0
  private String ReadWholeFileToString(String filename) {

    File file = new File(filename);
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // show file contents here
    return contents.toString();
  }
Ejemplo n.º 21
0
  // Cleanup for disconnect
  private static void cleanUp() {
    try {
      if (hostServer != null) {
        hostServer.close();
        hostServer = null;
      }
    } catch (IOException e) {
      hostServer = null;
    }

    try {
      if (socket != null) {
        socket.close();
        socket = null;
      }
    } catch (IOException e) {
      socket = null;
    }

    try {
      if (in != null) {
        in.close();
        in = null;
      }
    } catch (IOException e) {
      in = null;
    }

    if (out != null) {
      out.close();
      out = null;
    }
  }
Ejemplo n.º 22
0
 public static String sendGet(String url, String params) {
   String result = "";
   BufferedReader in = null;
   try {
     String urlName = url + "?" + params;
     URL realUrl = new URL(urlName);
     URLConnection conn = realUrl.openConnection();
     conn.setRequestProperty("accept", "*/*");
     conn.setRequestProperty("connection", "Keep-Alive");
     conn.setRequestProperty(
         "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
     conn.connect();
     Map<String, List<String>> map = conn.getHeaderFields();
     for (String key : map.keySet()) {
       System.out.println(key + "--->" + map.get(key));
     }
     in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     String line;
     while ((line = in.readLine()) != null) {
       result += "\n" + line;
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (in != null) {
         in.close();
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return result;
 }
Ejemplo n.º 23
0
  private String getTitle(File f) {
    String result = "";
    if (!f.getName().endsWith(".html")) return "not HTML";
    else {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String ligne = reader.readLine();
        while (ligne != null && !ligne.contains("<TITLE>") && !ligne.contains("<title>")) {
          ligne = reader.readLine();
        }
        reader.close();
        if (ligne == null) return "No TITLE in page " + f.getName();
        else {
          String fin = "";
          String debut = "";
          if (ligne.contains("</TITLE>")) {
            debut = "<TITLE>";
            fin = "</TITLE>";
          } else if (ligne.contains("</title>")) {
            debut = "<title>";
            fin = "</title>";
          } else return "No title in page " + f.getName();

          int fin_index = ligne.lastIndexOf(fin);
          result = ligne.substring(ligne.indexOf(debut) + 7, fin_index);
          return result;
        }
      } catch (Exception e) {
        LOG.error("Error while reading file " + e);
        return "Error for file " + f.getName();
      }
    }
  }
Ejemplo n.º 24
0
  public static void main(String args[]) throws IOException {

    try {
      // Create a URL object

      String temp =
          "http://ccnabaaps.hostingsiteforfree.com/folder/phppart.php?q=http://www.espncricinfo.com/india/content/player/253802.html";
      URL url = new URL(temp);

      // Read all of the text returned by the HTTP server
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

      String htmlText;

      while ((htmlText = in.readLine()) != null) {
        // Keep in mind that readLine() strips the newline characters
        System.out.println(htmlText);
      }
      in.close();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 25
0
  /**
   * Main run loop for the Receiver. Continuously reads from input until a null is passed,
   * terminating the receiver.
   */
  public void run() {
    try
    // main run loop
    {
      String line;

      while ((line = input.readLine()) != null) {
        world.receive(name, line);
      }
    } catch (SocketException se) {
      world.setMessage("Your opponent has disconnected.");
    } catch (Exception e) {
      e.printStackTrace();
    }
    // end loop

    try
    // terminating
    {
      world.destroySocket(name);
      input.close();
      socket.close();
    } catch (Exception e) {
    }

    System.out.println(getName() + " terminating");
  }
Ejemplo n.º 26
0
  /**
   * Method to return a set of hazard data within CACHE_DISTANCE of given location
   *
   * @param location An instance of Location that stores latitude and longitude data
   * @return JSONObject an instance of JSONObject with json encoded hazard data
   * @throws IOException
   * @throws JSONException
   */
  public static JSONObject getHazards(LatLng location) throws IOException, JSONException {
    // request hazards from long / lat data and retrieve json hazards
    // tested and working!

    String longitude = String.valueOf(location.longitude);
    String latitude = String.valueOf(location.latitude);

    String query = String.format("longitude=%s&latitude=%s", longitude, latitude);
    // encode the post query

    // Set a POST connection
    URL url = new URL(site + "/request.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println(query);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();

    BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer hazards = new StringBuffer();
    String inputLine;
    while ((inputLine = response.readLine()) != null) {
      hazards.append(inputLine);
    }

    response.close();

    return new JSONObject(hazards.toString());
  }
Ejemplo n.º 27
0
  void writeoneline(String filename1, String filename2) throws IOException {
    // open the file for reading
    BufferedReader file = new BufferedReader(new FileReader(filename1));

    String line = null;
    // send message
    System.out.println("Sending message to the server...");

    while ((line = file.readLine()) != null) {
      String onebyone = line;
      output.println(onebyone);
    }
    file.close();

    // open the file for reading
    PrintWriter file2 = new PrintWriter(new BufferedWriter(new FileWriter(filename2)));
    String line2 = input.readLine();
    // receive a message
    // String response = input.readLine();
    if (line2.isEmpty()) System.out.println("(server did not reply with a message)");
    else {
      System.out.println("Writing to file...:");
      // String line= null;

      file2.println(line2);
      file2.close();
    }
    System.out.println("Done!");
  }
Ejemplo n.º 28
0
  private void processRequest() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    DataOutputStream writer = new DataOutputStream(socket.getOutputStream());

    try {
      request.parseRequest(reader);
    } catch (HttpRequestException e) {
      System.out.println(e.getMessage());
      ResponseCode = 400;
      ResponseReason = "Bad Request";
    }

    if (isCrawlingRequest()) {
      CrawlerHandler crawler = new CrawlerHandler(GetDomainFromRequest());
      crawler.StartCrawling();
    }

    checkTypeOfResponse();

    writer.write(createHTTPResponseHeaders().getBytes());
    writer.write(createHTTPResponseBody(writer));
    writer.write(CRLF.getBytes());

    writer.flush();
    writer.close();
    reader.close();
  }
Ejemplo n.º 29
0
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
Ejemplo n.º 30
0
 /**
  * Get the noun and verb <roots> (i.e. 'the highest' synsets in WordNet) from the particular
  * 'icfile' (Information Content) that you are applying. Store a noun <root>: a synset offset
  * number of type Integer in nounroots: an ArrayList<Integer> defined in the constructor of this
  * class. Store a verb <root>: a synset offset number of type Integer in verbroots: an
  * ArrayList<Integer> defined in the constructor of this class.
  *
  * <p>An example line in an 'icfile', showing a noun <root>: 1740n 128767 ROOT
  */
 private void getRoots() {
   Pattern pn = Pattern.compile("[0-9]+n [0-9]+ ROOT"); // find noun <root>
   Pattern pv = Pattern.compile("[0-9]+v [0-9]+ ROOT"); // find verb <root>
   Matcher m = null;
   String root = "";
   try {
     BufferedReader in = new BufferedReader(new FileReader(icfile));
     String line;
     while ((line = in.readLine()) != null) {
       // nouns
       m = pn.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("n")[0]; // !!! double split !!!
         nounroots.add(Integer.parseInt(root));
       }
       // verbs
       m = pv.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("v")[0]; // !!! double split !!!
         verbroots.add(Integer.parseInt(root));
       }
     }
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }