我正在尝试使用 java 制作一个简单的 http 客户端服务器。它将显示客户端的请求以及服务器的响应。例如服务器将发回
HTTP/1.0 200 OK
Connection: Close. etc.
以前我有一个回显客户端服务器。现在我已经把我的 echo 服务器变成了一个 http 服务器。我已经尝试过 Goggling 关于如何实现 head 并与客户端取得联系,但我注意到通常所有示例都使用 apache 框架。有没有办法在没有 apache 框架的情况下实现这些方法。我正在尝试将其转换为 http 客户端的回显客户端:
import java.io.*;
import java.net.*;
public class Ec1
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1", 80);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do
{
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err)
{
System.err.println(err);
}
}
}
我的 Http 服务器:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Echo
{
protected void start() {
ServerSocket s;
System.out.println("Webserver starting up on port 80");
try {
// create the main server socket
s = new ServerSocket(80);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = s.accept();
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
String str = ".";
while (!str.equals(""))
str = in.readLine();
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
out.println("");
out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
out.flush();
clientSocket.close();
s.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public static void main(String args[]) {
WebServer ws = new WebServer();
ws.start();
}
}