相思资源网 Design By www.200059.com
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 " ");
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);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com
暂无Java 实现 web服务器的简单实例的评论...
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。