示例#1
1
  public void run() {
    if (ServerSocket == null) return;
    while (true) {
      try {
        InetAddress address;
        int port;
        DatagramPacket packet;
        byte[] data = new byte[1460];
        packet = new DatagramPacket(data, data.length);
        ServerSocket.receive(packet);
        //
        //
        address = packet.getAddress();
        port = packet.getPort();
        System.out.println("get the Client port is: " + port);
        System.out.println("get the data length is: " + data.length);

        FileWriter fw = new FileWriter("Fortunes.txt");
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < data.length; i++) {
          out.print(data[i] + "  ");
        }
        out.close();
        System.out.println("Data has been writen to destination!");

        packet = new DatagramPacket(data, data.length, address, port);
        ServerSocket.send(packet);
        System.out.println("Respond has been made!");
      } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
      }
    }
  }
示例#2
0
文件: F.java 项目: 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();
    }
  }
  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 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();
  }
  private void sendProcessingError(Throwable t, ServletResponse response) {

    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {

      try {

        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    }
  }
示例#6
0
 public static void main(String[] args) {
   try {
     ServerSocket server = null;
     try {
       server = new ServerSocket(4700);
     } catch (Exception e) {
       System.out.println("Can Not Listem To:" + e);
     }
     Socket socket = null;
     try {
       socket = server.accept();
     } catch (Exception e) {
       System.out.println("Error: " + e);
     }
     String line;
     BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     PrintWriter os = new PrintWriter(socket.getOutputStream());
     BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("Client:" + is.readLine());
     line = sin.readLine();
     while (!line.equals("bye")) {
       os.println(line);
       os.flush();
       System.out.println("Server:" + line);
       System.out.println("Client:" + is.readLine());
       line = sin.readLine();
     }
     os.close();
     is.close();
     socket.close();
     server.close();
   } catch (Exception e) {
     System.out.println("Error:" + e);
   }
 }
示例#7
0
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    String base;
    System.out.println("What is the base URL?");
    base = input.nextLine();
    System.out.println("Generating . . .");
    Set<String> scanned = new HashSet<String>();
    Set<String> newLinks =
        new HashSet<String>(genSitemap(base, base)); // base href <a> tags index.html
    Set<String> incScanned = new HashSet<String>();
    List<List<String>> pages = new ArrayList<List<String>>();

    do {

      for (String a : newLinks) { // load base links, get <a> href for each
        scanned.add(a);
        System.out.println(a);
        incScanned.addAll(genSitemap(a, base));
      }

      for (String a : scanned) {
        // System.out.println(a);
        pages.add(getImgs(a));
      }

      newLinks.addAll(incScanned); // update base href list w/ found links
      newLinks.removeAll(scanned); // remove links which are already scanned
    } while (newLinks.size() != 0); // repeat scan/filter until no new links found

    for (List page : pages) {
      String[] ary = ((List<String>) page).toArray(new String[page.size()]);
      for (String src : ary) {
        System.out.println(src);
      }
    }
    try {
      PrintWriter writer = new PrintWriter("sitemap.xml", "UTF-8");
      writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      writer.println("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");
      writer.println("xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\">");
      for (List page : pages) {
        writer.println("<url>");
        writer.println("<loc>" + page.get(0) + "</loc>");
        page.remove(0);
        String[] ary = ((List<String>) page).toArray(new String[page.size()]);
        for (String src : ary) {
          writer.println("");
          writer.println("<image:image>");
          writer.println("<image:loc>" + src.replace("../", "") + "</image:loc>");
          writer.println("</image:image>");
        }
        writer.println("</url>");
      }
      writer.println("</urlset>");

      writer.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
示例#8
0
  /**
   * 向服务器发送命令行,给服务器端处理
   *
   * @param lines 命令行
   */
  public static void clientSend(String[] lines) {
    if (lines != null && lines.length <= 0) {
      return;
    }
    Socket socket = null;
    PrintWriter writer = null;
    try {
      socket = new Socket("localhost", port);

      writer =
          new PrintWriter(
              new BufferedWriter(
                  new OutputStreamWriter(
                      socket.getOutputStream(), EncodeConstants.ENCODING_UTF_8)));
      for (int i = 0; i < lines.length; i++) {
        writer.println(lines[i]);
      }

      writer.flush();
    } catch (Exception e) {
      FRContext.getLogger().error(e.getMessage(), e);
    } finally {
      try {
        writer.close();
        socket.close();
      } catch (IOException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
  }
  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);
    }
  }
  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;
    }
  }
示例#11
0
  /** Write file with position and size of the login box */
  public static void writePersistence() {

    Messages.postDebug("LoginBox", "LoginBox.writePersistence");
    // If the panel has not been created, don't try to write a file
    if (position == null) return;

    String filepath = FileUtil.savePath("USER/PERSISTENCE/LoginPanel");

    FileWriter fw;
    PrintWriter os;
    try {
      File file = new File(filepath);
      fw = new FileWriter(file);
      os = new PrintWriter(fw);
      os.println("Login Panel");

      os.println(height);
      os.println(width);
      double xd = position.getX();
      int xi = (int) xd;
      os.println(xi);
      double yd = position.getY();
      int yi = (int) yd;
      os.println(yi);

      os.close();
    } catch (Exception er) {
      Messages.postError("Problem creating  " + filepath);
      Messages.writeStackTrace(er);
    }
  }
示例#12
0
  public void go() {

    try {
      ServerSocket serverSock = new ServerSocket(4242);

      System.out.println(getTime() + "서버가 준비되었습니다.");
      // ServerSocket을 통해 이 서버 애플리케이션은 이 코드가 실행되고 있는 시스템의 4242번 포트로 들어오는 클라이언트 요청을 감시한다.

      while (true) {
        System.out.println(getTime() + "연결요청을 기다립니다.");
        Socket sock = serverSock.accept();
        sock.setSoTimeout(2000);
        // accept()메소드는 요청이 들어 올때까지 그냥 기다린다. 그리고 클라이언트 요청이 들어오면 클라이언트와 통신을 위해 (현재 쓰이고 있찌 않은 포트에 대한)
        // Socket을 리턴함.
        System.out.println(getTime() + sock.getInetAddress() + "로부터 연결요청이 들어왔습니다.");

        PrintWriter writer = new PrintWriter(sock.getOutputStream());
        String advice = getAdvice();
        writer.println(advice);
        writer.close();
        // 이제 클라이언트에 대한 Socket연결을 써서 PrintWriter를 만들고 클라이언트에 String 조언메시지를 보냄(println() 메소드 사용)
        // 그리고 나면 클라이언트와의 작업이 끝난 것이므로 Socket을 닫는다.

        System.out.println(advice);
      }

    } catch (IOException ex) {
      System.out.println("ssss");
      ex.printStackTrace();
    }
  } // go 메소드
示例#13
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;
    }
  }
示例#14
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();
    }
  }
示例#15
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!");
  }
示例#16
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;
  }
示例#17
0
  public static void main(String[] args) throws IOException {

    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
      System.err.println("Could not listen on port: " + PORT + ".");
      System.exit(1);
    }

    while (true) {

      Socket clientSocket = null;
      try {
        clientSocket = serverSocket.accept();
        startTime = System.currentTimeMillis();
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }

      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      String inputLine, outputLine;

      while ((inputLine = in.readLine()) != null) {

        if (messageCount.get(clientSocket) == null) {
          messageCount.put(clientSocket, 1);
        } else {
          messageCount.put(clientSocket, messageCount.get(clientSocket) + 1);
        }

        overallMessageCount += 1;
        System.out.println("---------------------------------------");
        System.out.println("Client: " + clientSocket.toString());
        System.out.println(
            "aktive since " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");
        System.out.println(new Date(System.currentTimeMillis()));
        System.out.println("Overall Message Count: " + overallMessageCount);
        System.out.println("Message Count from Client: " + messageCount.get(clientSocket));
        System.out.println("Message " + inputLine);
        System.out.println("---------------------------------------");
        outputLine = inputLine.toUpperCase();

        if (outputLine.equals("END")) {
          out.println("abort");
          break;
        }
        out.println(outputLine);
      }
      out.close();
      in.close();
      clientSocket.close();

      System.out.println("All Closed");
    }
    // serverSocket.close();
  }
 public void tearDownConnection() {
   try {
     socketWriter.close();
     socketReader.close();
   } catch (IOException e) {
     System.out.println("Error tearing down socket connection: " + e);
   }
 }
示例#19
0
 public static void make_output(float Sk[])
     throws FileNotFoundException, UnsupportedEncodingException {
   PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
   float temp = (float) 10.0;
   for (int i = 0; i < Sk.length; i++) {
     writer.println(String.valueOf(Sk[i]));
   }
   writer.close();
 }
示例#20
0
 public boolean saveToFile(String filename) {
   try {
     PrintWriter pw = new PrintWriter(new FileWriter(new File(filename)));
     pw.println(buffer.toString());
     pw.close();
     return true;
   } catch (Exception e) {
     return false;
   }
 }
示例#21
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);
    }
  }
示例#22
0
  private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException {

    NameValuePair<Long> run = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c;
    if (host.proxyHost != null)
      c =
          (HttpURLConnection)
              target.openConnection(
                  new Proxy(
                      Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort)));
    else c = (HttpURLConnection) target.openConnection();

    try {
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();

    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();

      // The input is a one liner in the form runId\tAge
      byte[] buffer = new byte[256]; // Very little cost for this new/GC.
      int size = is.read(buffer);

      // We have to close the input stream in order to return it to
      // the cache, so we get it for all content, even if we don't
      // use it. It's (I believe) a bug that the content handlers used
      // by getContent() don't close the input stream, but the JDK team
      // has marked those bugs as "will not fix."
      is.close();

      StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n");
      run = new NameValuePair<Long>();
      run.name = t.nextToken();
      run.value = Long.parseLong(t.nextToken());
    } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) {
      logger.warning("Polling " + target + " got response code " + responseCode);
    }
    return run;
  }
  private void saveData(TelemetryData data) {
    PrintWriter out;
    boolean newFile = false;

    if (saveCnt > 25000) {
      File logFile;
      int i;

      logFile = new File(telemetryDir + 99 + ".log");
      logFile.delete();
      newFile = true;

      for (i = 99; i > 0; i--) {
        logFile = new File(telemetryDir + (i - 1) + ".log");
        logFile.renameTo(new File(telemetryDir + i + ".log"));
      }
      saveCnt = 0;
    }

    try {
      String text = "";
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMAN);

      saveCnt++;
      out = new PrintWriter(new FileOutputStream(telemetryDir + "0.log", true));
      if (newFile) {
        text =
            "Time\tLatitude\tLongitude\tSpeed\tAcceleration X\tAcceleration Y\tAcceleration Z\tCoG\tOrientation Y\tOrientation Z\n\n";
        out.print(text);
      }
      text = dateFormat.format(new Date(System.currentTimeMillis())) + "\t";
      if (posValid) text = text + lastLat + "\t" + lastLon + "\t" + m_lastSpeed + "\t";
      else text = text + "-\t-\t-\t";
      text =
          text
              + data.getAccelX()
              + "\t"
              + data.getAccelY()
              + "\t"
              + data.getAccelZ()
              + "\t"
              + data.CoG
              + "\t"
              + data.getOrientY()
              + "\t"
              + data.getOrientZ()
              + "\n\n";
      out.print(text);
      out.close();
    } catch (IOException ioe) {
    }
  }
示例#24
0
 public void disconnect() {
   int cmdID = commID++;
   this.connected = false;
   try {
     out.println(cmdID + ";logout");
     out.flush();
     in.close();
     out.close();
     socket.close();
   } catch (IOException ex) {
     System.err.println("Server stop failed.");
   }
 }
示例#25
0
 /**
  * Preprocesses the messages from the server
  *
  * @param message
  */
 private synchronized void preprocessServerMessage(String message) {
   if (message == null) {
     this.stop();
     try {
       reader.close();
       writer.close();
     } catch (IOException ioe) {
       ioe.printStackTrace();
     }
     sendMessage(CLIENT, "Connection Closed by Server");
     _group = "";
   } else if (message.equals("") == false) processServerMessage(message);
 }
示例#26
0
  public void run() {
    while (true) {
      try {
        // wczytujemy co zostalo przyslane
        str = in.readLine();

        if (str.startsWith("ADDNEW:")) {
          System.out.println("trying to handle Add New User request...");
          if (!this.handleAddNew(str.substring(7))) {
            break;
          }
          continue;
        }
        if (str.startsWith("LOGIN:"******"trying to handle Login User request...");
          if (!this.handleLogin(str.substring(6))) {
            break;
          }
          continue;
        }

        if (str.startsWith("MSG:")) {
          System.out.println("trying to handle send message request...");
          if (!this.handleMsg(str.substring(4))) {
            break;
          }
          continue;
        }

        if (str.startsWith("LOGOUT")) {
          System.out.println("trying to log out user: "******"logged out user: userId");
          }
        }
      }
    }
    try {
      in.close();
      out.close();
      s.close();
    } catch (IOException e) {
    }
  }
示例#27
0
  public Duder(String args[]) {

    getConnected(args);

    play();

    try {
      sin.close();
      sout.close();
      s.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
示例#28
0
 public void run() {
   sc = new Scanner(System.in);
   String choice;
   while (true) {
     // Show the menu and wait for a choice.
     System.out.println(
         "Bank menu: (1)Set new MOTD, (2)Show all users, " + "(3)Save user data and quit");
     choice = sc.nextLine();
     switch (choice) {
       case "1":
         // Wait for a new MOTD.
         System.out.println("Type in a new MOTD if wanted.");
         String newMOTD = sc.nextLine();
         // If the new MOTD is not longer than 80 characters set the current motd to the new one.
         if (newMOTD.length() <= 80) {
           motd = newMOTD;
           System.out.println("New motd: " + motd);
           // Set the new motd in all sessions.
           for (int i = 0; i < sessions.size(); i++) {
             sessions.get(i).setMotd(motd);
           }
         }
         // If too long, show an error message.
         else {
           System.out.println("MOTD too long. Try again.");
         }
         break;
       case "2":
         // Print all user information with the users built-in toString().
         for (int i = 0; i < users.size(); i++) {
           System.out.println(users.get(i));
         }
         break;
       case "3":
         try {
           // Print all the users information to a text file and terminate the server.
           PrintWriter out = new PrintWriter(new FileWriter("users.txt"));
           for (int i = 0; i < users.size(); i++) {
             out.println(users.get(i).export());
           }
           out.close();
           System.exit(1);
         } catch (IOException e) {
           e.printStackTrace();
         }
       default:
         break;
     }
   }
 }
 public static void savePluginsList(Collection<String> ids, boolean append, File plugins)
     throws IOException {
   if (!plugins.isFile()) {
     FileUtil.ensureCanCreateFile(plugins);
   }
   PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(plugins, append)));
   try {
     for (String id : ids) {
       printWriter.println(id);
     }
     printWriter.flush();
   } finally {
     printWriter.close();
   }
 }
示例#30
0
  public static String getStackTrace(Throwable t) {

    String stackTrace = null;

    try {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      t.printStackTrace(pw);
      pw.close();
      sw.close();
      stackTrace = sw.getBuffer().toString();
    } catch (Exception ex) {
    }
    return stackTrace;
  }