Guest User

ClientConnectionHandler

a guest
Sep 2nd, 2025
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.04 KB | Source Code | 0 0
  1. package org.example;
  2.  
  3. import org.example.configFiles.Config;
  4. import org.example.configFiles.Route;
  5. import org.example.configFiles.Service;
  6.  
  7. import java.io.*;
  8. import java.net.Socket;
  9.  
  10. public class Client implements Runnable {
  11.  
  12.     private Socket clientSocket;
  13.     private Socket serviceSocket;
  14.     private Config configFile;
  15.     private ByteArrayOutputStream requestBytes;
  16.     private Service service;
  17.  
  18.     /**
  19.      * Constructor for the client connection.
  20.      *
  21.      * @param clientSocket Socket of the client who started the connection.
  22.      */
  23.     public Client(Socket clientSocket, Config configFile) {
  24.         this.clientSocket = clientSocket;
  25.         this.configFile = configFile;
  26.     }
  27.  
  28.     /**
  29.      * Reads the input stream and write it into the output stream.
  30.      *
  31.      * @param input  The input stream, where the data are read.
  32.      * @param output The output stream, where the data are written.
  33.      */
  34.     private void copyData(InputStream input, OutputStream output) {
  35.         byte[] buffer = new byte[4096];
  36.         int byteRead;
  37.  
  38.         try {
  39.             while ((byteRead = input.read(buffer)) != -1) {
  40.                 output.write(buffer, 0, byteRead);
  41.             }
  42.             output.flush();
  43.         } catch (Exception e) {
  44.             System.out.println("Reading stream error: " + e.getMessage());
  45.         }
  46.     }
  47.  
  48.     /**
  49.      *
  50.      * @param request The http header where the HttpRequestHandler object will find the path
  51.      * @return
  52.      */
  53.     public Service findRoutes(String request) {
  54.         HttpRequestHandler handler = new HttpRequestHandler(request);
  55.         String path = handler.getPath();
  56.         for(Route r : configFile.getRoutes())
  57.         {
  58.             if(r.getPath().equals(path)){
  59.                 return r.getService().getFirst();
  60.             }
  61.         }
  62.  
  63.         System.out.println("No route: " + path);
  64.         return null;
  65.     }
  66.  
  67.     /**
  68.      * Method that is responsible for the comunication between the client e the service host.
  69.      * Open the socket for the service, get the input streams and the output streams of both client and service sockets and swap them using the copyData() method.
  70.      */
  71.     public void run() {
  72.         System.out.println("New connection from: " + clientSocket.getRemoteSocketAddress());
  73.  
  74.         try {
  75.             clientSocket.setKeepAlive(true);
  76.             InputStream fromClient = clientSocket.getInputStream();
  77.             OutputStream toClient = clientSocket.getOutputStream();
  78.  
  79.             // --------------------------------------------------------
  80.             // Routing
  81.             // --------------------------------------------------------
  82.             // Read a chunk of 4096 bytes of the HTTP request
  83.             requestBytes = new ByteArrayOutputStream();
  84.             byte[] buffer = new byte[4096];
  85.             int bytesRead;
  86.  
  87.             bytesRead = fromClient.read(buffer);
  88.             if (bytesRead == -1) {
  89.                 System.out.println("Empty client request.");
  90.                 return;
  91.             }
  92.             requestBytes.write(buffer, 0, bytesRead);
  93.  
  94.             // Parsing to a string the chunks of bytes
  95.             String requestLine = requestBytes.toString("UTF-8").split("\r\n")[0];
  96.             System.out.println("First line: " + requestLine);
  97.  
  98.  
  99.             // Find the correct host and port
  100.             service = findRoutes(requestLine);
  101.             if (service == null) {
  102.                 System.out.println("No route: " + requestLine);
  103.                 return;
  104.             }
  105.             System.out.println("Connection to " + service.getHost() + ":" + service.getPort());
  106.  
  107.             serviceSocket = new Socket(service.getHost(), service.getPort());
  108.             InputStream fromService = serviceSocket.getInputStream();
  109.             OutputStream toService = serviceSocket.getOutputStream();
  110.  
  111.             // Write the bytes already read
  112.             System.out.println("Http request: " + requestBytes);
  113.             toService.write(requestBytes.toByteArray());
  114.             toService.flush();
  115.  
  116.             // --------------------------------------------------------
  117.             // Proxy loop full-duplex
  118.             // --------------------------------------------------------
  119.             Thread serviceToClient= new Thread(() -> copyData(fromService, toClient));
  120.             serviceToClient.start();
  121.  
  122.             Thread clientToService = new Thread(() -> copyData(fromClient, toService));
  123.             clientToService.start();
  124.  
  125.             clientToService.join();
  126.             serviceToClient.join();
  127.         } catch (Exception e) {
  128.             System.out.println("Error: " + e.getMessage());
  129.         } finally {
  130.             try {
  131.                 if (!clientSocket.isClosed() && clientSocket != null)
  132.                     clientSocket.close();
  133.                 if (!serviceSocket.isClosed() && serviceSocket != null)
  134.                     serviceSocket.close();
  135.             } catch (IOException e) {
  136.                 System.out.println("Socket closing error: " + e.getMessage());
  137.             }
  138.         }
  139.     }
  140. }
  141.  
Advertisement
Add Comment
Please, Sign In to add comment