更新時間:2022-09-14 12:15:02 來源:動力節(jié)點 瀏覽1504次
在日常的開發(fā)中,我們用過很多開源的web服務(wù)器,例如tomcat、apache等等。現(xiàn)在我們自己實現(xiàn)一個簡單的web服務(wù)器,基本的功能就是用戶點擊要訪問的資源,服務(wù)器將資源發(fā)送到客戶端的瀏覽器。web服務(wù)基于的是HTTP協(xié)議,用戶在瀏覽器的地址欄輸入要訪問的地址,服務(wù)器如何得到該地址是個關(guān)鍵。先看下一般的HTTP請求和響應(yīng)報文的一般格式:
HTTP 請求報文
HTTP 響應(yīng)報文
socket類套接字是網(wǎng)絡(luò)連接的斷點。套接字使得應(yīng)用程序可以從網(wǎng)絡(luò)中讀取數(shù)據(jù),可以向網(wǎng)絡(luò)中寫入數(shù)據(jù)。不同計算機上的應(yīng)用程序可以通過套接字發(fā)送或接受字節(jié)流。java中提供了Socket類來實現(xiàn)這個功能,通過getInputStream和getOutputStream可以獲取網(wǎng)絡(luò)中的輸入輸出流。 但是,光靠Socket類還是不能夠?qū)崿F(xiàn)我們構(gòu)建一個服務(wù)器應(yīng)用程序的功能的,因為服務(wù)器必須時刻待命,因此java里面提供了ServerSocket類來處理等待來自客戶端的請求,當(dāng)ServerSocket接受到了來自客戶端的請求之后,它就會創(chuàng)建一個實例來處理與客戶端的通信。
服務(wù)器應(yīng)用程序的實現(xiàn) 首先,我們要構(gòu)建一個封裝請求信息的類requst,一個響應(yīng)請求的類response,還要有一個主程序httpServer來處理客戶端來的請求。
下面是代碼:
Request類:
package server;
import java.io.IOException;
import java.io.InputStream;
/**
* 將瀏覽器發(fā)來的請求信息轉(zhuǎn)化成字符和截取url
*/
public class Request {
//輸入流
private InputStream input;
//截取url,如http://localhost:8080/index.html ,截取部分為 /index.html
private String uri;
public Request(InputStream inputStream){
this.input = inputStream;
}
public InputStream getInput() {
return input;
}
public void setInput(InputStream input) {
this.input = input;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
//從套接字中讀取字符信息
public void parse(){
StringBuffer request = new StringBuffer(2048);
int i = 0;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
i = -1;
}
for(int j = 0;j
request.append((char)(buffer[j]));
}
System.out.println(request.toString());
uri = parseUri(request.toString());
}
//截取請求的url 截取index.html
private String parseUri(String requestString){
int index1 = 0;
int index2 = 0;
index1 = requestString.indexOf(' ');
if(index1!=-1){
index2 = requestString.indexOf(' ',index1+1);
if(index2>index1){
return requestString.substring(index1+1,index2);
}
}
return null;
}
}
Responselei
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
/**
* 類說明 根據(jù)相應(yīng)信息返回結(jié)果
*/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output){
this.output = output;
}
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
File file = new File(HttpServer.WEB_ROOT,request.getUri());
if(file.exists()){
try {
fis = new FileInputStream(file);
int ch = fis.read(bytes,0,BUFFER_SIZE);
while(ch != -1){
output.write(bytes,0,ch);
ch = fis.read(bytes,0,BUFFER_SIZE);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fis !=null){
fis.close();
}
}
}else{
//找不到文件
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"
File Not Found
";
try {
output.write(errorMessage.getBytes());
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Request getRequest() {
return request;
}
public void setRequest(Request request) {
this.request = request;
}
public OutputStream getOutput() {
return output;
}
public void setOutput(OutputStream output) {
this.output = output;
}
public static int getBUFFER_SIZE() {
return BUFFER_SIZE;
}
}
HttpServer類
package server;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
類說明
時刻等待前端請求
*/
public class HttpServer {
/**
* @param args
*/
//WEB_ROOT是服務(wù)器的根目錄
public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot";
//關(guān)閉的命令
// private static final String SHUTDOWN_COMMAND= "/SHUTDOWN";
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpServer server = new HttpServer();
server.await();
}
public void await(){
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
while(true)
{
try {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
封裝request請求
Request request = new Request(input);
request.parse();
封裝response對象
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上就是關(guān)于“Java實現(xiàn)Web服務(wù)器的代碼”介紹,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點的Java視頻教程,里面的課程內(nèi)容從入門到精通,細(xì)致全面,通俗易懂,適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家的學(xué)習(xí)能夠有所幫助。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743