Java实现一个简单的Web服务器端程序,该程序监听TCP 80端口,能够接受传入的HTTP连接请求并进行解析,并且能够正确的响应请求,回送相关的网页,还有一个客户端发送HTTP连接请求并接收响应网页
时间: 2024-03-20 21:42:13 浏览: 66
好的,下面是一个Java实现的简单Web服务器端程序和一个客户端程序,可以满足您的要求:
服务器端程序:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleWebServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(80);
} catch (IOException e) {
System.out.println("Error: Could not connect to port 80!");
System.exit(1);
}
System.out.println("Web server is running on port 80 ...");
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String line = in.readLine();
while (line != null && !line.equals("")) {
System.out.println(line);
line = in.readLine();
}
String response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Hello, world!</h1></body></html>\r\n";
out.write(response.getBytes());
out.flush();
out.close();
in.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
```
客户端程序:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class SimpleWebClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 80);
OutputStream out = socket.getOutputStream();
String request = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
out.write(request.getBytes());
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = in.readLine();
while (line != null && !line.equals("")) {
System.out.println(line);
line = in.readLine();
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
上述程序中,服务器端程序通过创建ServerSocket对象监听80端口,并且循环接受客户端连接请求,处理请求报文并生成响应报文。客户端程序通过创建Socket对象连接到服务器端,发送HTTP请求报文并接收响应报文。
当客户端运行SimpleWebClient程序时,会向服务器端发送HTTP请求报文,服务器端会返回一个简单的HTML网页。客户端程序将收到的响应报文输出到控制台。
需要注意的是,这只是一个简单的实现,还有很多需要完善的地方,例如支持多线程处理客户端连接请求、支持处理不同类型的HTTP请求等。
阅读全文