Java编写http服务器和http客户端,客户端能与服务端连接并展示响应成果服务器多线程处理客户端请求,可以实现GET、HEAD、POST请求,可以通过浏览器查看服务器信息的代码

时间: 2024-02-15 22:04:13 浏览: 23
以下是Java编写HTTP服务器和客户端的示例代码: HTTP服务器: ```java import java.io.*; import java.net.*; import java.util.*; public class HTTPServer implements Runnable { private Socket clientSocket; public HTTPServer(Socket clientSocket) { this.clientSocket = clientSocket; } public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(8080); System.out.println("HTTP Server is running on port 8080."); while (true) { Socket clientSocket = serverSocket.accept(); Thread thread = new Thread(new HTTPServer(clientSocket)); thread.start(); } } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); OutputStream out = clientSocket.getOutputStream(); String requestLine = in.readLine(); System.out.println(requestLine); String[] tokens = requestLine.split("\\s+"); String method = tokens[0]; String uri = tokens[1]; if (method.equals("GET")) { doGet(uri, out); } else if (method.equals("HEAD")) { doHead(uri, out); } else if (method.equals("POST")) { doPost(uri, in, out); } else { doError(HttpStatus.BAD_REQUEST, out); } clientSocket.close(); } catch (IOException e) { System.err.println(e); } } private void doGet(String uri, OutputStream out) throws IOException { File file = new File("." + uri); if (file.exists() && file.isFile()) { byte[] bytes = readFile(file); out.write(getResponse(HttpStatus.OK, bytes.length, "text/html").getBytes()); out.write(bytes); } else { doError(HttpStatus.NOT_FOUND, out); } } private void doHead(String uri, OutputStream out) throws IOException { File file = new File("." + uri); if (file.exists() && file.isFile()) { byte[] bytes = readFile(file); out.write(getResponse(HttpStatus.OK, bytes.length, "text/html").getBytes()); } else { doError(HttpStatus.NOT_FOUND, out); } } private void doPost(String uri, BufferedReader in, OutputStream out) throws IOException { int contentLength = 0; String line; while ((line = in.readLine()) != null) { if (line.equals("")) { break; } if (line.startsWith("Content-Length: ")) { contentLength = Integer.parseInt(line.substring("Content-Length: ".length())); } } if (contentLength > 0) { char[] buffer = new char[contentLength]; in.read(buffer, 0, contentLength); String requestBody = new String(buffer); System.out.println(requestBody); } out.write(getResponse(HttpStatus.OK, 0, "text/html").getBytes()); } private void doError(HttpStatus status, OutputStream out) throws IOException { out.write(getResponse(status, 0, "text/html").getBytes()); } private String getResponse(HttpStatus status, int contentLength, String contentType) { StringBuilder sb = new StringBuilder(); sb.append("HTTP/1.1 ").append(status.getCode()).append(" ").append(status.getMessage()).append("\r\n"); sb.append("Content-Length: ").append(contentLength).append("\r\n"); sb.append("Content-Type: ").append(contentType).append("\r\n"); sb.append("\r\n"); return sb.toString(); } private static byte[] readFile(File file) throws IOException { FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; fileInputStream.read(bytes); fileInputStream.close(); return bytes; } } enum HttpStatus { OK(200, "OK"), BAD_REQUEST(400, "Bad Request"), NOT_FOUND(404, "Not Found"); private final int code; private final String message; HttpStatus(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } ``` HTTP客户端: ```java import java.io.*; import java.net.*; public class HTTPClient { public static void main(String[] args) throws Exception { String method = "GET"; String uri = "/"; String requestBody = ""; if (args.length > 0) { method = args[0]; } if (args.length > 1) { uri = args[1]; } if (args.length > 2) { requestBody = args[2]; } Socket socket = new Socket("localhost", 8080); OutputStream out = socket.getOutputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.write((method + " " + uri + " HTTP/1.1\r\n").getBytes()); out.write("Host: localhost\r\n".getBytes()); out.write("Connection: close\r\n".getBytes()); if (method.equals("POST")) { out.write(("Content-Length: " + requestBody.length() + "\r\n").getBytes()); out.write("Content-Type: application/x-www-form-urlencoded\r\n".getBytes()); } out.write("\r\n".getBytes()); if (method.equals("POST")) { out.write(requestBody.getBytes()); } String line; while ((line = in.readLine()) != null) { System.out.println(line); } socket.close(); } } ``` 以上代码实现了一个简单的HTTP服务器和客户端,服务器支持多线程处理客户端请求,可以处理GET、HEAD、POST请求,并且可以通过浏览器查看服务器信息。

相关推荐

最新推荐

recommend-type

java多线程实现服务器端与多客户端之间的通信

本篇文章主要介绍了java多线程实现服务器端与多客户端之间的通信,介绍了多线程来实现服务器与多线程之间的通信的基本步骤,有需要的小伙伴可以参考下。
recommend-type

Java基于socket实现的客户端和服务端通信功能完整实例

主要介绍了Java基于socket实现的客户端和服务端通信功能,结合完整实例形式分析了Java使用socket建立客户端与服务器端连接与通信功能,需要的朋友可以参考下
recommend-type

详解C# Socket简单例子(服务器与客户端通信)

主要介绍了详解C# Socket简单例子(服务器与客户端通信) ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
recommend-type

C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析

主要介绍了C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析,包括websocket sharp组件的概念及使用方法,需要的朋友可以参考下
recommend-type

python网络编程socket实现服务端、客户端操作详解

主要介绍了python网络编程socket实现服务端、客户端操作,结合实例形式分析了python基于socket实现服务端、客户端相关操作技巧与使用注意事项,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】增量式PID的simulink仿真实现

# 2.1 Simulink仿真环境简介 Simulink是MATLAB中用于建模、仿真和分析动态系统的图形化环境。它提供了一个直观的用户界面,允许用户使用块和连接线来创建系统模型。Simulink模型由以下元素组成: - **子系统:**将复杂系统分解成更小的、可管理的模块。 - **块:**代表系统中的组件,如传感器、执行器和控制器。 - **连接线:**表示信号在块之间的流动。 Simulink仿真环境提供了广泛的块库,涵盖了各种工程学科,包括控制系统、电子和机械工程。它还支持用户自定义块的创建,以满足特定仿真需求。 # 2. Simulink仿真环境的搭建和建模 ### 2.
recommend-type

训练集和测试集的准确率都99%,但是预测效果不好

即使训练集和测试集的准确率都很高,但是在实际的预测中表现不佳,可能会有以下几个原因: 1. 数据质量问题:模型训练和测试的数据可能存在问题,比如数据标签错误、数据集采样不均衡、数据集中存在异常值等问题,这些问题可能会导致模型在实际预测中表现不佳。 2. 特征工程问题:模型的特征工程可能存在问题,导致模型无法很好地捕捉数据的特征,从而影响预测效果。 3. 模型选择问题:模型的选择可能不合适,比如选择的模型太简单,无法很好地拟合数据,或者选择的模型太复杂,导致过拟合等问题。 4. 超参数调整问题:模型的超参数可能没有调整到最佳状态,需要进行调整。 针对以上可能的原因,可以采取相应的措施进
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。