java 实现 web服务器的简单实例
实例代码:
import java.util.*;
// chapter 8, listing 3
public class webserverdemo {
// directory of html pages and other files
protected string docroot;
// port number of web server
protected int port;
// socket for the web server
protected serversocket ss;
// handler for a http request
class handler extends thread {
protected socket socket;
protected printwriter pw;
protected bufferedoutputstream bos;
protected bufferedreader br;
protected file docroot;
public handler(socket _socket, string _docroot) throws exception {
socket = _socket;
// get the absolute directory of the filepath
docroot = new file(_docroot).getcanonicalfile();
}
public void run() {
try {
// prepare our readers and writers
br = new bufferedreader(new inputstreamreader(
socket.getinputstream()));
bos = new bufferedoutputstream(socket.getoutputstream());
pw = new printwriter(new outputstreamwriter(bos));
// read http request from user (hopefully get /file...... )
string line = br.readline();
// shutdown any further input
socket.shutdowninput();
if (line == null) {
socket.close();
return;
}
if (line.touppercase().startswith("get")) {
// eliminate any trailing ? data, such as for a cgi get
// request
stringtokenizer tokens = new stringtokenizer(line, " ?");
tokens.nexttoken();
string req = tokens.nexttoken();
// if a path character / or / is not present, add it to the
// document root
// and then add the file request, to form a full filename
string name;
if (req.startswith("/") || req.startswith("//"))
name = this.docroot + req;
else
name = this.docroot + file.separator + req;
// get absolute file path
file file = new file(name).getcanonicalfile();
// check to see if request doesn't start with our document
// root ....
if (!file.getabsolutepath().startswith(
this.docroot.getabsolutepath())) {
pw.println("http/1.0 403 forbidden");
pw.println();
}
// ... if it's missing .....
else if (!file.exists()) {
pw.println("http/1.0 404 file not found");
pw.println();
}
// ... if it can't be read for security reasons ....
else if (!file.canread()) {
pw.println("http/1.0 403 forbidden");
pw.println();
}
// ... if its actually a directory, and not a file ....
else if (file.isdirectory()) {
senddir(bos, pw, file, req);
}
// ... or if it's really a file
else {
sendfile(bos, pw, file.getabsolutepath());
}
}
// if not a get request, the server will not support it
else {
pw.println("http/1.0 501 not implemented");
pw.println();
}
pw.flush();
bos.flush();
} catch (exception e) {
e.printstacktrace();
}
try {
socket.close();
} catch (exception e) {
e.printstacktrace();
}
}
protected void sendfile(bufferedoutputstream bos, printwriter pw,
string filename) throws exception {
try {
java.io.bufferedinputstream bis = new java.io.bufferedinputstream(
new fileinputstream(filename));
byte[] data = new byte[10 * 1024];
int read = bis.read(data);
pw.println("http/1.0 200 okay");
pw.println();
pw.flush();
bos.flush();
while (read != -1) {
bos.write(data, 0, read);
read = bis.read(data);
}
bos.flush();
} catch (exception e) {
pw.flush();
bos.flush();
}
}
protected void senddir(bufferedoutputstream bos, printwriter pw,
file dir, string req) throws exception {
try {
pw.println("http/1.0 200 okay");
pw.println();
pw.flush();
pw.print("<html><head><title>directory of ");
pw.print(req);
pw.print("</title></head><body><h1>directory of ");
pw.print(req);
pw.println("</h1><table border=/"0/">");
file[] contents = dir.listfiles();
for (int i = 0; i < contents.length; i++) {
pw.print("<tr>");
pw.print("<td><a href="/" rel="external nofollow" rel="external nofollow" mce_href="/" rel="external nofollow" rel="external nofollow" "");
pw.print(req);
pw.print(contents[i].getname());
if (contents[i].isdirectory())
pw.print("/");
pw.print("/">");
if (contents[i].isdirectory())
pw.print("dir -> ");
pw.print(contents[i].getname());
pw.print("</a></td>");
pw.println("</tr>");
}
pw.println("</table></body></html>");
pw.flush();
} catch (exception e) {
pw.flush();
bos.flush();
}
}
}
// check that a filepath has been specified and a port number
protected void parseparams(string[] args) throws exception {
switch (args.length) {
case 1:
case 0:
system.err.println("syntax: <jvm> " + this.getclass().getname()
+ " docroot port");
system.exit(0);
default:
this.docroot = args[0];
this.port = integer.parseint(args[1]);
break;
}
}
public webserverdemo(string[] args) throws exception {
system.out.println("checking for paramters");
// check for command line parameters
parseparams(args);
system.out.print("starting web server...... ");
// create a new server socket
this.ss = new serversocket(this.port);
system.out.println("ok");
for (;;) {
// accept a new socket connection from our server socket
socket accept = ss.accept();
// start a new handler instance to process the request
new handler(accept, docroot).start();
}
}
// start an instance of the web server running
public static void main(string[] args) throws exception {
webserverdemo webserverdemo = new webserverdemo(args);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!