Java语言编写简易Web 服务器, 具体的过程和步骤分为: 1.当一个客户(浏览器)连接时,创建一个连接套接字; 2.从这个连接套接字接收 HTTP 请求; 3.解释该请求以确定所请求的特定文件; 4.从服务器的文件系统获得请求的文件; 5.创建一
时间: 2024-02-12 12:06:58 浏览: 89
个 HTTP 响应消息,包括状态行,消息报头和响应正文; 6.将响应消息通过连接套接字发送回客户端(浏览器)。
下面是一个简单的Java代码实现Web服务器的基本框架:
```java
import java.io.*;
import java.net.*;
public class SimpleWebServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080); //创建ServerSocket,监听8080端口
System.out.println("Web server running on port 8080");
while (true) {
Socket clientSocket = serverSocket.accept(); //等待客户端连接
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //获取输入流
String request = in.readLine(); //读取HTTP请求
String[] tokens = request.split("\\s+"); //将请求按空格分割
String method = tokens[0]; //获取请求方法
String path = tokens[1]; //获取请求路径
if (method.equals("GET")) { //只处理GET请求
File file = new File("." + path); //获取请求的文件
if (file.exists()) { //如果文件存在
OutputStream out = new BufferedOutputStream(clientSocket.getOutputStream()); //获取输出流
String contentType = guessContentType(path); //猜测内容类型
byte[] data = readFile(file); //读取文件内容
sendHeader(out, "HTTP/1.1 200 OK", contentType, data.length); //发送响应头
out.write(data); //发送响应正文
out.flush();
} else { //如果文件不存在
OutputStream out = clientSocket.getOutputStream();
String errorMessage = "404 Not Found";
out.write(("HTTP/1.1 " + errorMessage + "\r\n").getBytes());
out.write(("Content-Type: text/plain\r\n").getBytes());
out.write(("Content-Length: " + errorMessage.length() + "\r\n").getBytes());
out.write(("\r\n").getBytes());
out.write(errorMessage.getBytes());
out.flush();
}
}
clientSocket.close(); //关闭连接
}
}
private static String guessContentType(String path) { //猜测内容类型
if (path.endsWith(".html") || path.endsWith(".htm")) {
return "text/html";
} else if (path.endsWith(".gif")) {
return "image/gif";
} else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
return "image/jpeg";
} else if (path.endsWith(".png")) {
return "image/png";
} else {
return "application/octet-stream";
}
}
private static byte[] readFile(File file) throws IOException { //读取文件内容
InputStream in = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
in.close();
return out.toByteArray();
}
private static void sendHeader(OutputStream out, String statusLine, String contentType, int contentLength) throws IOException { //发送响应头
out.write((statusLine + "\r\n").getBytes());
out.write(("Content-Type: " + contentType + "\r\n").getBytes());
out.write(("Content-Length: " + contentLength + "\r\n").getBytes());
out.write(("\r\n").getBytes());
}
}
```
在浏览器中打开 http://localhost:8080/,即可访问服务器。这里的服务器只能处理静态文件,如果需要处理动态内容,需要使用其他框架或技术。
阅读全文
相关推荐

















