Processing sketch as a web page server

Hello folks!

Processing sketch as a web page server:

// Processing sketch as a web page server
// Author: glv
// Date:   2025-09-22
// Insight gleaned from various sources; seek and you shall find!

// You will see this in code:
// https://github.com/processing/processing/issues/3937

// Sketch will launch this:
// Wep Page server at http://127.0.0.1:20000/1

import processing.net.*;

Server s;
Client c;

String incoming;

String time;
int count = 0;

void setup()
  {
  size(200, 200, P2D);
  
  // Starts a myServer on port 20000
  s = new Server(this, 20000);

  link("http://127.0.0.1:20000/1"); // Comment this if it does now work and lauhc browser manually!
  delay(500);
  }

void draw()
  {
  background(255);
  fill(0);
  
  // Reference:
  //<h3>Count:</h3>
  //<h3>%d</h3>
  //<h3>Time:</h3>
  //<h3>%s</h3>
  
  textSize(24);
  String txt = "Count:\r\n" + count + 
               "\r\n\r\n" + 
               "Time:\r\n" + time; 
  
  text(txt, 50, 50);
  }

void clientEvent(Client c) 
    { 
    incoming = c.readString();
    println("Received:\r\n"+ incoming);
    
    time = nf(hour(),2) + ":" + nf(minute(),2) + ":" + nf(second(), 2);
    println(time);
    
    incoming = incoming.substring(0, incoming.indexOf("\r\n")); // Only up to the newline
    if (incoming.equals("GET /1 HTTP/1.1"))
      {
      webPage(time, count);     
      count++;
      println("Count sent: " + count);
      println();
      println("*************************************************************");
      println();
      redraw();
      }
  }

void webPage(String _time, int _count) 
  {    
  
  String htmlContent = """
        <!DOCTYPE html>
        <html>
            <head>
                <meta http-equiv="refresh" content="1">
                <link rel="icon" href="data:,">
                <title>Live Counter</title>
            </head>
            <body>
                <h3>Count:</h3>
                <h3>%d</h3>
                <h3>Time:</h3>
                <h3>%s</h3>
            </body>
        </html>
        """.stripIndent().formatted(_count, _time);

String httpResponse = """
        HTTP/1.1 200 OK
        Content-Length: %d
        Content-Type: text/html
        Connection: close
        
        %s
        """.stripIndent().formatted(htmlContent.length(), htmlContent);

  // Send the complete HTTP response
  s.write(httpResponse.getBytes());
  // println(httpResponse);
  }  


Learned something new:

That was fun!

:)

6 Likes

This is great @glv – thanks for sharing! Just started making networked sketches with my AP CSP class and will try this out with them soon.

1 Like