CSC220 Processing and Web Access Examples

From dftwiki3
Revision as of 23:35, 9 November 2010 by Thiebaut (talk | contribs) (Created page with ' <center> <font size="+2">Page under construction!</font> <br \>300px </center> =Example 1= * This example written in Processing gets the content…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Page under construction!
UnderConstruction.jpg

Example 1

  • This example written in Processing gets the contents of an html file, square.htm, containing this contents:
4
5 5
5 10
10 10
10 5
  • The first line contains 4, indicating that there are 4 points. The next 4 lines contain the x and y coordinates of the 4 points.
  • The file is stored on http://cs.smith.edu/~thiebaut/temp/square.htm
  • The Processing script shown below reads the contents of the file and displays the square formed by the 4 points.
import processing.net.*;

//--- Globals ---
Client c;
String data;
int delta = 5;

//-------------------------------------------------------------
//--- Setup: initializes the client and sets the display ---
void setup() {
  size(60, 60);
  background(50);
  fill(100);
  stroke( 255 );

  //--- open up a client and request the page of interest ---
  c = new Client( this, "maven.smith.edu", 80 );
  c.write("GET /~thiebaut/temp/square.htm\n"); 
  c.write("Host: my_domain_name.com\n\n"); 

  //--- set frame rate to once a second ---
  frameRate( 1 );
}


//-------------------------------------------------------------
// draw(): gets the contents of the file, if available, 
//            and displays it.
//-------------------------------------------------------------
void draw() {

  //--- any data? ---
  if (c.available() > 0) {  
    data = c.readString();  

    String[] lines = split( data, '\n' );

    //--- got some lines? ---
    if ( lines.length > 0 ) {
      //--- assume first number on a line by itself is # of points ---
      int n = int( lines[0] );

      //--- declare x and y arrays of  n points ---
      float[] x = new float[ n ];
      float[] y = new float[ n ];

      //--- fill x and y arrays with coordinates from file ---
      for ( int i = 1; i <= n; i++ ) {
        float[] nums = float( split( lines[i], ' ' ) );
        x[ i-1 ] = nums[ 0 ];
        y[ i-1 ] = nums[ 1 ];
      } 

      //--- display lines between the points ---
      for ( int j = 0; j < n-1; j++ ) 
        line( x[j], y[j], x[(j+1) ], y[(j+1)] );
      line( x[n-1], y[n-1], x[0], y[0] );
    }
  }
}