java服務(wù)器的簡單實現(xiàn)過程記錄
?一、HTTP
?http請求
?一般一個http請求包括以下三個部分:
?1 請求方法,如get,post
?2 請求頭
?3 實體
?一個http請求的實例如下:
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,這是我們待會要截取出來的。
?http響應(yīng)
與http請求類似,http響應(yīng)也包括三個部分
1 協(xié)議-狀態(tài)碼-描述
2 響應(yīng)頭
3 響應(yīng)實體段
二 socket類
套接字是網(wǎng)絡(luò)連接的斷點(diǎn)。套接字使得應(yīng)用程序可以從網(wǎng)絡(luò)中讀取數(shù)據(jù),可以向網(wǎng)絡(luò)中寫入數(shù)據(jù)。不同計算機(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來處理客戶端來的請求。
package com.lwq;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joker
* 類說明
* 將瀏覽器發(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<i;j++){
request.append((char)(buffer[j]));
}
System.out.println(request.toString());
uri = parseUri(request.toString());
}
//截取請求的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)請求的類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)建時間: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;
}
}
接下來是主程序,
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請求
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();
}
}
}
運(yùn)行httpServer,在瀏覽器中打下http://localhost:8080/index.jsp,就能看到服務(wù)器響應(yīng)的結(jié)果了。
總結(jié)
到此這篇關(guān)于java服務(wù)器的簡單實現(xiàn)的文章就介紹到這了,更多相關(guān)java服務(wù)器實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring security獲取用戶信息的實現(xiàn)代碼
這篇文章主要介紹了spring security獲取用戶信息的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請求數(shù)據(jù)丟失問題
這篇文章主要介紹了解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請求數(shù)據(jù)丟失問題,主要包括無異步線程得情況下feign遠(yuǎn)程調(diào)用,異步情況下丟失上下文問題,需要的朋友可以參考下2022-05-05
Java?Stream函數(shù)式編程管道流結(jié)果處理
這篇文章主要為大家介紹了Java?Stream函數(shù)式編程管道流結(jié)果處理的示例過程解析需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
基于JPA實體類監(jiān)聽器@EntityListeners注解的使用實例
這篇文章主要介紹了JPA實體類監(jiān)聽器@EntityListeners注解的使用實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

