Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using TcpSocket to Create a Simple HTTP Server
#1
For a long time, I have been using the following PowerShell code to create a temporary HTTP server. The actual code is only about 20 lines, but it consumes more than 30 MB of background resources.

I want to achieve similar functionality using TcpSocket because it is more resource-efficient.
Sending commands from Android+Tasker to QM

I tried using ChatGPT to help implement this functionality, but I haven't had any luck...

Thanks in advance for any suggestions or help!

 
Code:
Copy      Help
cls

$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:8080/") # Create an HTTP listener

$webRoot = $PSScriptRoot # Specify the website root directory

$listener.Start() # Start the listener
Write-Host "HTTP server is running at http://localhost:8080/"
start http://localhost:8080/

while ($true) {
    try {        
        $context = $listener.GetContext() # Wait for a request
        
        # Get the request and response objects
        $request = $context.Request
        $response = $context.Response
        
        # Get the file path, default to returning index.html
        $requestedFile = if ($request.Url.AbsolutePath.Substring(1) -eq "") { "index.html" } else { $request.Url.AbsolutePath.Substring(1) }
        $filePath = Join-Path $webRoot $requestedFile
        
        if (Test-Path $filePath) {
            # Determine the file type and set the response
            if ($filePath.EndsWith(".html")) {
                $fileContent = Get-Content $filePath -Raw
                $fileBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
                $response.ContentType = "text/html"
            } elseif ($filePath.EndsWith(".png")) {
                $fileBytes = [System.IO.File]::ReadAllBytes($filePath)
                $response.ContentType = "image/png"
            }          
            $response.StatusCode = 200 # Send the file content
            $response.OutputStream.Write($fileBytes, 0, $fileBytes.Length)
        } else {            
            $response.StatusCode = 404 # Return a 404 error
            $response.StatusDescription = "Not Found"
            $errorBytes = [System.Text.Encoding]::UTF8.GetBytes("404 - File Not Found")
            $response.OutputStream.Write($errorBytes, 0, $errorBytes.Length)
        }
    } catch {      
        $response.StatusCode = 500 # Handle exceptions
        $response.StatusDescription = "Internal Server Error"
    } finally {      
        $response.OutputStream.Close() # Close the response stream
    }
}

$listener.Stop() # Stop the listener


Attached Files
.zip   Http_Test.zip (Size: 702.61 KB / Downloads: 8)


Forum Jump:


Users browsing this thread: 1 Guest(s)