java Socket簡(jiǎn)單模擬HTTP服務(wù)器。

<h3>最近復(fù)習(xí)計(jì)算機(jī)網(wǎng)絡(luò),復(fù)習(xí)完應(yīng)用層之后對(duì)于理論知識(shí)還是沒(méi)有一個(gè)深刻的概念,索性就動(dòng)手用Java Socket API 模擬做一個(gè)HTTP服務(wù)器,鞏固一下應(yīng)用層的知識(shí)。</h3>
<blockquote>
HTTP基于TCP協(xié)議,協(xié)議采用了請(qǐng)求/響應(yīng)模型??蛻?hù)端向服務(wù)器發(fā)送一個(gè)請(qǐng)求,請(qǐng)求頭包含請(qǐng)求的方法、URL、協(xié)議版本、以及包含請(qǐng)求修飾符、客戶(hù)信息和內(nèi)容的類(lèi)似于MIME的消息結(jié)構(gòu)。服務(wù)器以一個(gè)狀態(tài)行作為響應(yīng),響應(yīng)的內(nèi)容包括消息協(xié)議的版本,成功或者錯(cuò)誤編碼加上包含服務(wù)器信息、實(shí)體元信息以及可能的實(shí)體內(nèi)容——百度百科。

話(huà)不多說(shuō),還是直接上圖。
</blockquote>

http.png

具體字段這里不作解釋?zhuān)欢恼?qǐng)先自己了解http協(xié)議。這里主要是根據(jù)請(qǐng)求響應(yīng)這一過(guò)程模擬HTTP服務(wù)器。
下面是代碼:
<pre>

package com.example.httpserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    private static final Integer port = 80;//HTTP默認(rèn)端口80
    
    public static void main(String[] args) {
        ServerSocket serverSocket;
        
        try {
            //建立服務(wù)器Socket,監(jiān)聽(tīng)客戶(hù)端請(qǐng)求
            serverSocket = new ServerSocket(port);
            System.out.println("Server is running on port:"+serverSocket.getLocalPort());
            //死循環(huán)不間斷監(jiān)聽(tīng)客戶(hù)端請(qǐng)求
            while(true){
                final Socket socket = serverSocket.accept();
                System.out.println("biuld a new tcp link with client,the cient address:"+  
                        socket.getInetAddress()+":"+socket.getPort());
                //并發(fā)處理HTTP客戶(hù)端請(qǐng)求
                service(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void service(Socket socket)
    {
        new Thread(){
            public void run(){
                InputStream inSocket;
                try {
                    //獲取HTTP請(qǐng)求頭
                    inSocket = socket.getInputStream();
                    int size = inSocket.available();
                    byte[] buffer = new byte[size];
                    inSocket.read(buffer);
                    String request = new String(buffer);
                    System.out.println("ClientBrowser:\n"+request+"\n"
                            + "------------------------------------------------------------------");
                    
                    String firstLineOfRequest = "";
                    String[] heads;
                    String uri = "/index.html";
                    String contentType ="";
                    if(request.length() > 0){
                        firstLineOfRequest = request.substring(0,request.indexOf("\r\n"));
                        heads = firstLineOfRequest.split(" ");
                        uri = heads[1];
                        
                        if(uri.indexOf("html") != -1){
                            contentType = "text/html";
                        }else{
                            contentType = "application/octet-stream";
                        }
                    }
                    //將響應(yīng)頭發(fā)送給客戶(hù)端
                    String responseFirstLine = "HTTP/1.1 200 OK\r\n";
                    
                    String responseHead = "Content-Type:" + contentType +"\r\n";
                    
                    OutputStream outSocket = socket.getOutputStream();
                    System.out.println("ServerResponse:\n"+responseFirstLine+"\n"+responseHead+"\n"
                            + "--------------------------------------------------------------------");
                    outSocket.write(responseFirstLine.getBytes());
                    outSocket.write(responseHead.getBytes());
                    //通過(guò)HTTP請(qǐng)求中的uri讀取相應(yīng)文件發(fā)送給客戶(hù)端
                    FileInputStream writehtml = new FileInputStream(new File("wwwroot"+uri));
                    outSocket.write("\r\n".getBytes());  
                    byte[] htmlbuffer = new byte[writehtml.available()];
                    if(writehtml !=null){
                        int len = 0;
                        System.out.println("writeHtml");
                        while((len = writehtml.read(htmlbuffer)) != -1){
                            outSocket.write(htmlbuffer, 0,len);
                        }
                    }
                    outSocket.close();
                    socket.close();
                
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}

</pre>

代碼看注釋也很容易理解?,F(xiàn)在我們?cè)跒g覽器中輸入服務(wù)器地址+要訪(fǎng)問(wèn)的文件

request.png

在看我們控制臺(tái)輸出的內(nèi)容:

response.png

<h5>以上就是Java Socket 簡(jiǎn)單的模擬HTTP服務(wù)器全過(guò)程。</h5>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • API定義規(guī)范 本規(guī)范設(shè)計(jì)基于如下使用場(chǎng)景: 請(qǐng)求頻率不是非常高:如果產(chǎn)品的使用周期內(nèi)請(qǐng)求頻率非常高,建議使用雙通...
    有涯逐無(wú)涯閱讀 2,927評(píng)論 0 6
  • 一、概念(載錄于:http://www.cnblogs.com/EricaMIN1987_IT/p/3837436...
    yuantao123434閱讀 8,741評(píng)論 6 152
  • Http協(xié)議詳解 標(biāo)簽(空格分隔): Linux 聲明:本片文章非原創(chuàng),內(nèi)容來(lái)源于博客園作者M(jìn)IN飛翔的HTTP協(xié)...
    Sivin閱讀 5,345評(píng)論 3 82
  • 1 “小魚(yú),你睡著了啊,空調(diào)開(kāi)那么低,我得提醒你!”耳畔傳來(lái)了一個(gè)溫柔而誘惑的女聲。 “神仙,妖怪?謝謝!” “你...
    沖浪小魚(yú)兒閱讀 538評(píng)論 13 15

友情鏈接更多精彩內(nèi)容