# HTTP / Socket Server

### KHTTPServerThread / KSocketThread Class Overview

* **Socket and HTTP**\
  Supports raw TCP/IP socket applications or HTTP server applications (for web or REST services).
* **TLS and Non-TLS Client Connection Support**\
  Enables both secure (TLS) and non-secure client connections to server applications, providing flexibility for various networking scenarios.
* **Thread Management**\
  Loads, starts, and manages user classes to dynamically handle socket or HTTP clients.
* **Client and Basic Authentication**\
  Allows server applications to differentiate between authenticated and non-authenticated clients. Use the getAuthenticatedClient() method to verify a valid client name..
* **Flexible Data Read/Write Methods**\
  Includes efficient methods for reading and writing data in various formats, such as byte\[], char\[], String, and line-based input.

<details>

<summary>HTTP Server Example: Simple Webserver</summary>

```java
try (KSocketServer httpServer = new KSocketServer(8080, KHTTPServerThreadSample.class)) {

   if (!httpServer.isActive()) {
      System.out.println("The HTTP server could not be started: " + httpServer.getLastError());
      System.exit(1);
   }
			
   System.out.println("HTTP server ready on port 8080 - Will terminate after 3 minutes");
   K.waitMinutes(3);
   System.out.println("HTTP server terminating");
}
```

```java
public class KHTTPServerThreadSample extends KHTTPServerThread {

   public KHTTPServerThreadSample(Socket argSocket) {
      super(argSocket);
   }
	
   @Override
   public void get(String argURL) {
      sendFile(argURL);
   }
}
```

</details>

<details>

<summary>Socket Server Example: Echo Server</summary>

```java
// Start echo server on port 8080
try (KServerSocket server = New KServerSocket(8080, KSocketServerThreadSample.class)) {
   KLog.abort(!server.isActive(), "Unable to start server: " + server.getLastError());

   // Let client connect (e.g. "nc localhost 8080" or "telnet localhost 8080")
   K.waitMinutes(5);
}
```

```java
public class KSocketServerThreadSample extends KSocketServerThread {

   public KSocketServerThreadSample(Socket argSocket) {
      super(argSocket);
   }

   public void run() {
      KLog.info("Upper-Case-Echo-Server started");
      
      String newLine    = K.getLineSeparator();
      String clientData = null;
      
      write((!isSecuredConnection() ? "Non-" : "") + "TLS Upper-Case-Echo-Server ready" + newLine);
      
      while ((clientData = readLine()) != null) {
         write(clientData.toUpperCase() + newLine);
      }
      close();
      
      KLog.info("Upper-Case-Echo-Server terminated");
   }
}
```

</details>

### Architecture Overview

<figure><img src="https://1523050323-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FnLy540wu2J4F0Txdp4tM%2Fuploads%2FuLgH1C58On7VY1GlNRHU%2FKSocketServer.png?alt=media&#x26;token=e7563030-7d65-4855-aff1-59d50ed48582" alt=""><figcaption></figcaption></figure>
