ProxyServer.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 ServerSocket server;
  15. private Forwarder f;
  16. public static void main(String[] args) throws IOException, InterruptedException {
  17. //start a thread for a forwarder
  18. ProxyServer ps = new ProxyServer();
  19. ps.run();
  20. }
  21. public ProxyServer() throws IOException, InterruptedException {
  22. server = new ServerSocket(PORT, 1, InetAddress.getLocalHost());
  23. f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
  24. System.out.println("\r\nRunning Server: " + "Host=" + server.getInetAddress().getHostAddress() + " Port=" + server.getLocalPort() + " Hostname=" + server.getInetAddress().getHostName());
  25. }
  26. void run() throws IOException {
  27. //Thread t = new Thread(() -> {
  28. // try {
  29. // Forwarder f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
  30. // while (true) {
  31. // f.forward();
  32. // Thread.sleep(1000);
  33. // }
  34. // } catch (Exception e) {
  35. // e.printStackTrace();
  36. // }
  37. //});
  38. //t.start();
  39. ExecutorService executor = Executors.newCachedThreadPool();
  40. while (true) {
  41. //this will block until a connection is made
  42. Socket client = this.server.accept();
  43. executor.execute(new ServerThread(client));
  44. }
  45. }
  46. private class ServerThread implements Runnable {
  47. private Socket client;
  48. public ServerThread(Socket client) {
  49. this.client = client;
  50. System.out.println("New connection from " + client.getInetAddress().getHostAddress());
  51. }
  52. @Override
  53. public void run() {
  54. try {
  55. listen();
  56. this.client.close();
  57. System.exit(0);
  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. if(data.equals("end!")) {
  69. break;
  70. }
  71. System.out.println(client.getInetAddress().getHostAddress() + ": " + data);
  72. }
  73. }
  74. }
  75. }