代码实现-浏览器访问socket服务(简单)

前言

我们用过许多web服务器(Tomcat,Apache,WebLogic…)其实他们是功能很强大的socket服务,当我们在浏览器地址栏输入对应的IP地址,其实也就是浏览器创建了一个socket连接。那么服务端能否响应一段文字呢?


实现的功能

在浏览器地址栏输入:http://localhost:8888/index.html返回对应页面,如果没有就返回404,服务端用java编写的ServerSocket完成,并获取浏览器请求的内容。通过流,根据请求的路径,读取相应的html文件,并返回给浏览器。
这里写图片描述
这里写图片描述
这里写图片描述这里写图片描述


实现代码

package com.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @Author: cxx
 * @Date: 2018/6/20 15:20
 */
public class ServerTest {
    private static int port = 8888;
    private static Socket accept;
    private static ServerSocket socket;
    private static BufferedWriter bw;
    public static void main(String[] args) throws Exception {
        socket = new ServerSocket(port);
        System.out.println("服务器开启,等待连接....");
        while (true){
            accept = socket.accept();
            InputStreamReader r = new InputStreamReader(accept.getInputStream());
            System.out.println("浏览器请求成功!");
            BufferedReader br = new BufferedReader(r);
            String readLine = br.readLine();
            System.out.println("---------------------");
            //打印请求消息
            String filePath="log";
            int i=0;
            while(readLine != null && !readLine.equals("")){
                System.out.println(readLine);
                if (i==0){
                    String[] split = readLine.split(" ");
                    if (split[1].endsWith("html")) {
                        filePath += split[1];
                    }
                }
                i++;
                readLine=br.readLine();
            }
            System.out.println("----------------------");
            //发送响应请求
            System.out.println(filePath);
            writeHtml(filePath);
        }
    }

    public static void writeHtml(String filePath) throws Exception{
        if (!"log/index.html".equals(filePath)){
            filePath="log/404.html";
        }
        FileInputStream fis = new FileInputStream(filePath);
        int len=0;
        byte[] b = new byte[1024];
        StringBuilder sb = new StringBuilder();
        //拼装http响应的数据格式
        sb.append("http/1.1 200 ok").append("\n\n");
        while ((len=fis.read(b))!=-1){
            sb.append(new String(b,0,len));
        }
        bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
        bw.write(sb.toString());
        bw.flush();
        bw.close();
    }
}

注意

浏览器每次发起请求,都会同时请求一次favicon.ico(本次不讨论浏览器缓存了favicon.ico)。

浏览器请求成功!
---------------------
GET /index.html HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
----------------------
log/index.html
浏览器请求成功!
---------------------
GET /favicon.ico HTTP/1.1
Host: localhost:8888
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: http://localhost:8888/index.html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
----------------------
log
浏览器请求成功!

猜你喜欢

转载自blog.csdn.net/m0_37499059/article/details/80751758