最简单的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);
}
}