Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

Rendering dynamic web content

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code for the Web Server is as such:

import java.lang.*;
import java.net.*;
import java.io.File;
import java.io.IOException;

class Server
{
ThreadForTrans theThread;

public static void main( String args[] )
{
try
{
IO.Trace("STATE", "Web server 0.301" );
if ( args.length == 2 )
{
int port = Integer.parseInt( args[0] );// Port number
IO.Trace("STATE", "Base of file system : " + args[1] );
(new Server()).process( port, args[1] );// Start server
return; // Normal exit
}
}
catch ( Exception err )
{
IO.Error( "port not integer" ); // Integer port no
}
IO.Error( "Usage port FileBase" ); // Display usage
}

public void process( final int port, final String base )
{
try
{
ServerSocket ss = new ServerSocket(port); // Server Socket
while( true ) // Loop
{
Socket socket = ss.accept(); // Wait for connection
theThread = new ThreadForTrans(socket,base);// Create thread
// Either run as separate thread or serially
theThread.start(); // Start thread
//theThread.run(); // No thread
}
}
catch ( Exception err )
{
IO.Error("process: " + err.getMessage() );
}
}
}


class ThreadForTrans extends Thread
{
private Socket theSocket; // Socket used
private String baseDir = "/";
private NetInputStream theIn; // Input object stream
private NetOutputStream theOut;

public ThreadForTrans( Socket s, String base )
{
theSocket = s; // Socket used
baseDir = base; // Base of files
}

public void run() // Execution
{
IO.Trace( "STATE", "Open connection " );
try
{
theIn = new NetInputStream( theSocket ); // Input
theOut = new NetOutputStream( theSocket );// Output
String get = null;

while ( true )
{
String message = theIn.getLine(); // From Client
if ( message == null ) break; // No more data
IO.Trace( "REC ", message );

if ( startsWith( message, "GET " ) )
get = message.substring( 4 ); // Remember file name
if ( startsWith( message, "Host" ) )
{
sendFile( get ); // send file
get = null; // Reset
}
}

theIn.close(); // Close Read
theOut.close(); // Close Write
theSocket.close(); // Close Socket
}
catch( Exception err )
{
IO.Error("ThreadForTrans: " + err.getMessage() );
}
IO.Trace( "STATE", "Close connection" );
}

// Check if message starts with string

boolean startsWith( String message, String start )
{
return (message.toLowerCase()).startsWith( start.toLowerCase() );
}

// Send file to Client
// Extension used to define type of transfer

public void sendFile( String m ) throws IOException
{
if ( m == null ) return;

String file = baseDir + m.substring( 0, m.indexOf( ' ' ) );
String ext = file.substring( file.indexOf( '.' )+1 );
ext = ext.toLowerCase();

IO.Trace( "FILE", "File [" + file + "]" +
" Ext [" + ext + "]" );

File aFile = new File( file );
if ( aFile.canRead() )
{
theOut.putLine( "HTTP/1.1 200 OK ");
theOut.putLine( "Date: Fri, 31 Dec 2010 23:59:59 GMT");
theOut.putLine( "Server: Quick and simple");
theOut.putLine( "Content-length: " + aFile.length() );
theOut.putLine( "Connection: close");
if ( ext.equals( "jpg" ) || ext.equals( "jpeg" ))
{
theOut.putLine( "Content-type: image/jpg");
}

if ( ext.equals( "gif" ) )
{
theOut.putLine( "Content-type: image/gif");
}

if ( ext.equals( "png" ) )
{
theOut.putLine( "Content-type: image/png");
}

if ( ext.equals( "htm" ) || ext.equals( "html" ))
{
theOut.putLine( "Content-type: text/html ");
}
theOut.putLine( "" );
theOut.copyFile( file );
theOut.putLine( "" );
} else {
theOut.putLine( "HTTP/1.1 403 Problem " + file );
}
theOut.flush();
}

}
----------------------------
import java.io.*;
import java.net.*;

class NetInputStream extends BufferedInputStream
{
private String theMessage = null; //

public NetInputStream( Socket s ) throws IOException
{
super( s.getInputStream() );
}

public String getLine()
{
try
{
String res = ""; // Accumulating line
int c; // Character read
while ( true )
{
c = read(); // Next character
if ( c == '\n' ) return res; // End of line
if ( c == -1 ) return null; // End of file (EOF)
if ( c != '\r' ) // Ignore '\r'
{
res += (char) c; // Append
}
}
}
catch ( Throwable e ) { } // I/O error

return null; // Treat as EOF
}
}
--------------------------
import java.io.*;
import java.net.*;

class NetOutputStream extends BufferedOutputStream
{
private String theMessage = null; //

public NetOutputStream( Socket s ) throws IOException
{
super( s.getOutputStream() );
}

public void write( byte[] buf, int offset, int len )
throws IOException
{
super.write( buf, offset, len );
super.flush();
}

public void putLine( String message ) throws IOException
{
byte[] asBytes = (message + "\n").getBytes();
write( asBytes, 0, asBytes.length ); // Send Message
flush();
IO.Trace( "SENT", message );
}

public void copyFile( String fileName ) throws IOException
{
final int bufferSize = 4096;
byte buffer[] = new byte[bufferSize];

FileInputStream istream = new FileInputStream(fileName);
BufferedInputStream theBis = new BufferedInputStream(istream);

while ( true )
{
int len = theBis.read( buffer, 0, bufferSize );
if ( len < 0 ) break;
write( buffer, 0, len );
}
theBis.close();
istream.close();
flush();
putLine(" ");
IO.Trace( "FILE", "Sent " + fileName );
}

}
-------------------
import java.io.*;
import java.net.*;

class IO
{
public static void Trace( String state, String mes )
{
System.err.println( (state + " ").substring(0, 5) +
": " + mes );
}

public static void Error( String s )
{
System.err.println( "Error : " + s );
}
}
--------------------------------

Any ideas on how to write a HTML file using JSP or JavaScript to render dynamic content for a web page...I am clueless and need help!!!

Also how do I make this web server better?

Meena
 
Sheriff
Posts: 67580
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are you writing your own web server?
 
Meenakshi Seeballack
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am basically starting from scratch.
- Write web server
- Deliver dynamic pages to web server

I need to understand the most basic of basics since I then plan to build a multi-player game which would be played over the internet

I understand if I change the copyFile method in the NetOutputStream class to recognize a specific character I would be able to send requests which would say, when you see this specific character run this specific piece of code which could be in JSP, which would give it the "dynamic" characteristic

I am unsure...help?
 
Bear Bibeault
Sheriff
Posts: 67580
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I still don't understand the need to write your own web server whenso many free alternatives already exist, but if you are planning on also supporting dynamic templating such as JSP, you've got your work cut out for you. The JSP Specification is a large and complex one,

In any case, such an endeavor is well outside the scope of a forum on writing JSPs, so I've moved this to the Internet Protocols forum.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote my own HTTP server for my Wiki as a learning exercise. It's a big job; grab an existing server unless you have a ton of time or some very good reasons not to. (I thought I had both.) For a very tight example of a web server look into the FitNesse source code. If I'd seen that first, I probably wouldn't have done my own.

You can make up your own rendering scheme if you don't want to implement all of JSP. Typical Wiki markup is not that hard to render. FitNesse and FrikiWiki (and probably many others) do a neat job of it for examples.

I added syntax for macros ${name arg,arg} where name maps to a Java class that can do anything it likes and return markup and/or HTML. All this is simple text replacement, no looping or other control structures.
 
I'm still in control here. LOOK at this tiny ad!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic