當前位置:首頁 » 網頁前端 » java實現web伺服器
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

java實現web伺服器

發布時間: 2022-01-30 03:59:05

A. 如何用Java實現Web伺服器

如何用Java實現Web伺服器 一、HTTP協議的作用原理

WWW是以Internet作為傳輸媒介的一個應用系統,WWW網上最基本的傳輸單位是Web網頁。WWW的工作基於客戶機/伺服器計算模型,由Web 瀏覽器(客戶機)和Web伺服器(伺服器)構成,兩者之間採用超文本傳送協議(HTTP)進行通信。HTTP協議是基於TCP/IP協議之上的協議,是Web瀏覽器和Web伺服器之間的應用層協議,是通用的、無狀態的、面向對象的協議。HTTP協議的作用原理包括四個步驟:

(1) 連接:Web瀏覽器與Web伺服器建立連接,打開一個稱為socket(套接字)的虛擬文件,此文件的建立標志著連接建立成功。

(2) 請求:Web瀏覽器通過socket向Web伺服器提交請求。HTTP的請求一般是GET或POST命令(POST用於FORM參數的傳遞)。GET命令的格式為:

GET 路徑/文件名 HTTP/1.0

文件名指出所訪問的文件,HTTP/1.0指出Web瀏覽器使用的HTTP版本。

(3) 應答:Web瀏覽器提交請求後,通過HTTP協議傳送給Web伺服器。Web伺服器接到後,進行事務處理,處理結果又通過HTTP傳回給Web瀏覽器,從而在Web瀏覽器上顯示出所請求的頁面。

B. Java Web伺服器

我現寫了一個,可以訪問到靜態資源。你看情況多給點分吧
另外eclipse還沒有5.5,5.5的貌似是myEclipse吧

其中port指埠,默認是地址是http://127.0.0.1:8088/
其中basePath指資源根路徑,默認是d:
可以通過命令行參數對其進行賦值

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;

public class SimpleHttpServer {
private static int port = 8088;
private static String basePath = "D:/";

public static void main(String[] args) {
if (args.length >= 1) {
basePath = args[0];
}
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
System.out.println("server starting:");
System.out.println("base path:" + basePath);
System.out.println("Listening at:" + port);
startServer();
System.out.println("server started succesfully");
}

private static void startServer() {
new Thread() {
public void run() {
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
final Socket s = ss.accept();
new Thread() {
public void run() {
try {
OutputStream socketOs = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
String headerLine = null;
while ((line = br.readLine()) != null) {
if (headerLine == null) {
headerLine = line;
}
if ("".equals(line)) {
break;
}
}
String target = headerLine.replaceAll("^.+ (.+) HTTP/.+$", "$1");
String queryString;
String[] tmp = target.split("\\?");
target = URLDecoder.decode(tmp[0], "utf-8");
target = target.endsWith("/") ? target.substring(0, target.length() - 1) : target;
if (tmp.length > 1) {
queryString = tmp[1];
} else {
queryString = "";
}

String filePath = basePath + target;
File f = new File(filePath);

if (!f.exists()) {
StringBuffer content = new StringBuffer();
content.append("<html><head><title>Resource Not Found</title></head><body><h1>The requested resource ")
.append(target).append(" is not found.</h1></body></html>");
StringBuffer toWrite = new StringBuffer();
toWrite.append("HTTP/1.1 404 Not Found\r\nContent-Length:").append("" + content.length()).append("\r\n\r\n")
.append(content);
socketOs.write(toWrite.toString().getBytes());
} else if (f.isDirectory()) {
StringBuffer content = new StringBuffer();
content.append("<html><head><title>").append(target).append(
"</title></head><body><table border='1' width='100%'>");
content.append("<tr><th align='left' width='40px'>").append("Path").append("</th><td>").append(target.length()>0?target:"/")
.append("</td></tr>");
content.append("<tr><th align='left'>Type</th><th align='left'>Name</th></tr>");
if (!basePath.equals(filePath)) {
content.append("<tr><td>Directory</td><td>").append("<a href='").append(
target.substring(0, target.lastIndexOf("/") + 1)).append("'>..</a>").append("</td></tr>");
}
File[] files = f.listFiles();
for (File file : files) {
content.append("<tr><td>");
if (file.isFile()) {
content.append("File</td><td>");
} else if (file.isDirectory()) {
content.append("Directory</td><td>");
}
content.append("<a href=\"").append(target);
if (!(target.endsWith("/") || target.endsWith("\\"))) {
content.append("/");
}
content.append(file.getName()).append("\">").append(file.getName()).append("</a></td></tr>");
}
content.append("</table></body></html>");

StringBuffer sb = new StringBuffer();
sb.append("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\n");
sb.append("Content-Length:").append("" + content.length()).append("\r\n\r\n");
sb.append(content);
socketOs.write(sb.toString().getBytes());
} else if (f.isFile()) {
socketOs.write(("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\nContent-Length:" + f.length() + "\r\n\r\n")
.getBytes());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(f);
int cnt = 0;
while ((cnt = fis.read(buffer)) >= 0) {
socketOs.write(buffer, 0, cnt);
}
fis.close();
}
socketOs.close();
} catch (Exception e) {
try {
s.getOutputStream().write("HTTP/1.1 500 Error\r\n".getBytes());
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(byteos);
printStream
.write("<html><head><title>Error 500</title></head><body><h1>Error 500</h1><pre style='font-size:15'>"
.getBytes());
e.printStackTrace(printStream);
printStream.write("</pre><body></html>".getBytes());
byteos.close();
byte[] byteArray = byteos.toByteArray();
s.getOutputStream().write(("Content-Length:" + byteArray.length + "\r\n\r\n").getBytes());
s.getOutputStream().write(byteArray);
s.close();
} catch (IOException e1) {
e1.printStackTrace();
}

}
}
}.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}

C. 如何用JavaWeb實現這樣的文件伺服器

開放web目錄許可權即可

D. java web開發中伺服器端開發和web客戶端開發分別啥意思

你說錯了,web開發,是開發服務端的,因為你要把你開發好的web程序,打包成war,然後放到web容器中運行,而web容器,是部署在伺服器中的。
web的客戶端就是瀏覽器,所以,我個人猜想,它這里的客戶端,是不是指教你設計頁面,學CSS/HTML之類的。。
說錯了別噴,指導就好~~