ProxyServer.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package proxy;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.*;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.net.InetAddress;
  11. public class ProxyServer {
  12. public static List<String> MSGs = new ArrayList<>();
  13. private static final int PORT = 1234;
  14. private static final int roundLength = 3600; //secs
  15. private ServerSocket server;
  16. private Forwarder f;
  17. public static void main(String[] args) throws IOException, InterruptedException {
  18. //start a thread for a forwarder
  19. ProxyServer ps = new ProxyServer();
  20. ps.run();
  21. }
  22. public ProxyServer() throws IOException, InterruptedException {
  23. server = new ServerSocket(PORT, 1, InetAddress.getLocalHost());
  24. f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
  25. System.out.println("\r\nRunning Server: " + "Host=" + server.getInetAddress().getHostAddress() + " Port=" + server.getLocalPort() + " Hostname=" + server.getInetAddress().getHostName());
  26. }
  27. void run() throws IOException {
  28. //Thread t = new Thread(() -> {
  29. // try {
  30. // Forwarder f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
  31. // while (true) {
  32. // f.forward();
  33. // Thread.sleep(1000);
  34. // }
  35. // } catch (Exception e) {
  36. // e.printStackTrace();
  37. // }
  38. //});
  39. //t.start();
  40. ExecutorService executor = Executors.newCachedThreadPool();
  41. while (true) {
  42. //this will block until a connection is made
  43. Socket client = this.server.accept();
  44. executor.execute(new ServerThread(client));
  45. }
  46. }
  47. private class ServerThread implements Runnable {
  48. private Socket client;
  49. public ServerThread(Socket client) {
  50. this.client = client;
  51. System.out.println("New connection from " + client.getInetAddress().getHostAddress());
  52. }
  53. @Override
  54. public void run() {
  55. try {
  56. listen();
  57. this.client.close();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. void listen() throws IOException {
  63. BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  64. String data = null;
  65. while((data = in.readLine()) != null) {
  66. //MSGs.add(data);
  67. f.forwardDirectly(data);
  68. System.out.println(client.getInetAddress().getHostAddress() + ": " + data);
  69. }
  70. }
  71. }
  72. }