java服務(wù)器的簡(jiǎn)單實(shí)現(xiàn)過程記錄
?一、HTTP
?http請(qǐng)求
?一般一個(gè)http請(qǐng)求包括以下三個(gè)部分:
?1 請(qǐng)求方法,如get,post
?2 請(qǐng)求頭
?3 實(shí)體
?一個(gè)http請(qǐng)求的實(shí)例如下:
GET /index.jsp HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
注意紅色部分的url,這是我們待會(huì)要截取出來(lái)的。
?http響應(yīng)
與http請(qǐng)求類似,http響應(yīng)也包括三個(gè)部分
1 協(xié)議-狀態(tài)碼-描述
2 響應(yīng)頭
3 響應(yīng)實(shí)體段
二 socket類
套接字是網(wǎng)絡(luò)連接的斷點(diǎn)。套接字使得應(yīng)用程序可以從網(wǎng)絡(luò)中讀取數(shù)據(jù),可以向網(wǎng)絡(luò)中寫入數(shù)據(jù)。不同計(jì)算機(jī)上的應(yīng)用程序可以通過套接字發(fā)送或接受字節(jié)流。java中提供了Socket類來(lái)實(shí)現(xiàn)這個(gè)功能,通過getInputStream和getOutputStream可以獲取網(wǎng)絡(luò)中的輸入輸出流。
但是,光靠Socket類還是不能夠?qū)崿F(xiàn)我們構(gòu)建一個(gè)服務(wù)器應(yīng)用程序的功能的,因?yàn)榉?wù)器必須時(shí)刻待命,因此java里面提供了ServerSocket類來(lái)處理等待來(lái)自客戶端的請(qǐng)求,當(dāng)ServerSocket接受到了來(lái)自客戶端的請(qǐng)求之后,它就會(huì)創(chuàng)建一個(gè)實(shí)例來(lái)處理與客戶端的通信。
三 服務(wù)器應(yīng)用程序的實(shí)現(xiàn)
首先,我們要構(gòu)建一個(gè)封裝請(qǐng)求信息的類requst,一個(gè)響應(yīng)請(qǐng)求的類response,還要有一個(gè)主程序httpServer來(lái)處理客戶端來(lái)的請(qǐng)求。
package com.lwq;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joker
* 類說明
* 將瀏覽器發(fā)來(lái)的請(qǐng)求信息轉(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<i;j++){
request.append((char)(buffer[j]));
}
System.out.println(request.toString());
uri = parseUri(request.toString());
}
//截取請(qǐng)求的url
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;
}
}
下面是封裝了響應(yīng)請(qǐng)求的類response:
package com.lwq;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* @author Joker
* @version 創(chuàng)建時(shí)間:Sep 5, 2012 9:59:53 PM
* 類說明 根據(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;
}
}
接下來(lái)是主程序,
package com.lwq;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author Joker
* 類說明
*/
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請(qǐng)求
Request request = new Request(input);
request.parse();
//封裝response對(duì)象
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();
}
}
}
運(yùn)行httpServer,在瀏覽器中打下http://localhost:8080/index.jsp,就能看到服務(wù)器響應(yīng)的結(jié)果了。
總結(jié)
到此這篇關(guān)于java服務(wù)器的簡(jiǎn)單實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)java服務(wù)器實(shí)現(xiàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis Plus 自定義方法實(shí)現(xiàn)分頁(yè)功能的示例代碼
這篇文章主要介紹了Mybatis Plus 自定義方法實(shí)現(xiàn)分頁(yè)功能的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
深入了解Springboot核心知識(shí)點(diǎn)之?dāng)?shù)據(jù)訪問配置
這篇文章主要為大家介紹了Springboot核心知識(shí)點(diǎn)中的數(shù)據(jù)訪問配置,文中的示例代碼講解詳細(xì),對(duì)我們了解SpringBoot有一定幫助,快跟隨小編一起學(xué)習(xí)一下吧2021-12-12
詳解如何使用MyBatis簡(jiǎn)化JDBC開發(fā)
JavaEE?企業(yè)級(jí)?Java?項(xiàng)目中的經(jīng)典三層架構(gòu)為表現(xiàn)層,業(yè)務(wù)層和持久層.MyBatis?對(duì)?JDBC?代碼進(jìn)行了封裝,作為一款優(yōu)秀的持久層框架,專門用于簡(jiǎn)化JDBC開發(fā).本文主要介紹一下如何使用MyBatis簡(jiǎn)化JDBC開發(fā),需要的可以參考一下2023-01-01
Spring Data JPA+kkpager實(shí)現(xiàn)分頁(yè)功能實(shí)例
本篇文章主要介紹了Spring Data JPA+kkpager實(shí)現(xiàn)分頁(yè)功能實(shí)例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-06-06

