Java采用Socket技术编写http服务器和http客户端,服务器可以多线程处理客户端请求,以及实现HEAD、POST、GET请求的代码
时间: 2024-02-06 18:10:42 浏览: 73
以下是Java使用Socket技术编写HTTP服务器和客户端的示例代码(包括多线程处理客户端请求,以及实现HEAD、POST、GET请求):
HTTP服务器代码:
```java
import java.io.*;
import java.net.*;
public class HttpServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8080); // 创建服务器套接字
while (true) { // 循环监听客户端请求
Socket s = ss.accept(); // 等待客户端连接
new Thread(new Handler(s)).start(); // 创建线程处理客户端请求
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 读取客户端请求
String request = br.readLine();
String method = request.split("\\s+")[0]; // 获取请求方法
String url = request.split("\\s+")[1]; // 获取请求URL
String version = request.split("\\s+")[2]; // 获取HTTP版本号
System.out.println("Method: " + method);
System.out.println("URL: " + url);
System.out.println("Version: " + version);
while (br.readLine() != null) { // 忽略请求头部
if ("".equals(br.readLine())) {
break;
}
}
OutputStream os = socket.getOutputStream(); // 发送响应
if ("GET".equals(method)) { // 处理GET请求
File file = new File(url.substring(1));
if (file.exists() && !file.isDirectory()) {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
} else {
os.write("404 Not Found".getBytes());
}
} else if ("HEAD".equals(method)) { // 处理HEAD请求
File file = new File(url.substring(1));
if (file.exists() && !file.isDirectory()) {
os.write("HTTP/1.1 200 OK\r\n".getBytes());
os.write(("Content-Length: " + file.length() + "\r\n").getBytes());
os.write("\r\n".getBytes());
} else {
os.write("404 Not Found".getBytes());
}
} else if ("POST".equals(method)) { // 处理POST请求
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
os.write(("HTTP/1.1 200 OK\r\n\r\n" + sb.toString()).getBytes());
} else {
os.write("501 Not Implemented".getBytes());
}
os.flush();
os.close();
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
HTTP客户端代码:
```java
import java.io.*;
import java.net.*;
public class HttpClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 8080); // 创建客户端套接字,连接到服务器
OutputStream os = s.getOutputStream(); // 发送请求
String request = "GET /index.html HTTP/1.1\r\n" + "Host: localhost:8080\r\n" + "\r\n";
os.write(request.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); // 读取响应
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
os.close();
br.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:以上代码仅为示例,实际应用中需要考虑安全性、性能等因素。
阅读全文