Forwarder.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package proxy;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.net.InetAddress;
  5. import java.net.Socket;
  6. public class Forwarder {
  7. private Socket socket = null;
  8. public static boolean forwarderReady = false;
  9. private PrintWriter out;
  10. protected Forwarder(InetAddress serverAddress, int serverPort) throws IOException, InterruptedException {
  11. try {
  12. bindSocket(serverAddress, serverPort);
  13. } catch (Exception e) {
  14. System.out.println("Retrying...");
  15. Thread.sleep(5000);
  16. bindSocket(serverAddress, serverPort);
  17. }
  18. }
  19. private void bindSocket(InetAddress serverAddress, int serverPort) throws IOException {
  20. this.socket = new Socket(serverAddress, serverPort);
  21. while(!socket.isBound()) ;
  22. forwarderReady = true;
  23. out = new PrintWriter(this.socket.getOutputStream(), true);
  24. System.out.println("Connected to " + serverAddress.getHostAddress() + ":" + serverPort);
  25. }
  26. protected void forward() {
  27. System.out.println("Round ends. Forwarding...");
  28. StringBuilder messages = new StringBuilder();
  29. synchronized (ProxyServer.MSGs) {
  30. if(ProxyServer.MSGs.isEmpty())
  31. return;
  32. while (!ProxyServer.MSGs.isEmpty()) {
  33. out.write(ProxyServer.MSGs.remove(0) +"\n");
  34. out.flush();
  35. }
  36. }
  37. //System.out.println("Active closing");
  38. //this.socket.close();
  39. }
  40. protected void forwardDirectly(String data) {
  41. out.write(data+"\n");
  42. out.flush();
  43. //System.out.println("Active closing");
  44. //this.socket.close();
  45. }
  46. }