Java网络通信案例——B/S结构模拟

一、B/S结构

概念: B/S结构就是浏览器-服务器结构,浏览器通过网络传输协议与服务器进行通信的结构。

模拟B/S结构

public class BSserverDemo {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            ServerSocket socket = new ServerSocket(8080);
            new ServerThread(socket.accept()).start();
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

class ServerThread extends Thread{
    
    
    private Socket socket;

    public ServerThread(){
    
    }

    public ServerThread(Socket socket){
    
    
        this.socket = socket;
    }

    @Override
    public void run() {
    
    
        try {
    
    
            PrintStream ps = new PrintStream(socket.getOutputStream(),true);
            /*响应头*/
            ps.println("HTTP/1.1 200 OK");
            ps.println("Content-Type:text/html;charset=UTF-8");
            ps.println("");

            /*正文*/
            ps.println("<span>这就是我的响应头</span>");
            ps.close();
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

效果图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Zain_horse/article/details/131054093