最简单的http服务器试水

最简单的http服务器试水

总结一下: java还是爽,可以直接调用网络编程相关的
ServerSocket 和 Socket,一共四大块
(1) 服务器需要监听端口 ServerSocket(port)
(2) 一旦客户端发起连接请求,由于 http 协议是建立在 tcp/ip 协议上,所以需要通过 serversocket.accept()的返回值确定是否接收到请求
(3) 浏览器可能多次重连,或者取消连接
判断 clientsocket = null 或者 clientsocket.isclosed()
(4) 加上http协议的响应头部,注意空行 ‘\r\n’ + ‘响应正文’

package com.MyHttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
// 这里直接右键 Generate,然后 选择Override模块下5个
class myRuntimeError extends RuntimeException{
    public myRuntimeError() {
        super();
    }

    public myRuntimeError(String message) {
        super(message);
    }

    public myRuntimeError(String message, Throwable cause) {
        super(message, cause);
    }

    public myRuntimeError(Throwable cause) {
        super(cause);
    }

    protected myRuntimeError(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

public class HttpServer {
    public HttpServer(int port) throws IOException{
        if(port < 1 || port > 65535){
            new myRuntimeError("端口号错误,端口号必须在1到65535之间");
        }
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Http服务器启动,监听端口: " + port);

        while(true) {
            Socket clientSocket = serverSocket.accept();
            // 判断 clientSocket 仍启用
            System.out.println("接收客户端请求");
            if(clientSocket != null && !clientSocket.isClosed()){
                OutputStream clientOut = clientSocket.getOutputStream();
                clientOut.write("HTTP/1.1 200 ok\r\n".getBytes());
                clientOut.write("Server: myServer/1.0\r\n".getBytes());
                clientOut.write(("Date: " + (new Date()).toString() + "\r\n").getBytes());
                clientOut.write("Content-Type: text/html; charset = UTF-8\r\n".getBytes());
                clientOut.write("\r\n".getBytes());
                clientOut.write("<h1>Piao Piao is Da piao</h1>\r\n".getBytes());
                clientOut.flush();
                clientOut.close();
            }
        }
    }

    public static void main(String[] args) throws IOException{
        new HttpServer(54321);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值