我一直在尝试编写一个简单的 Web 服务器的开始,但似乎无法获得发送的响应。我已经尝试了所有可以想象的输出流类型,但似乎没有任何效果。我不知所措。这是我正在使用的两个类,对一些无关代码感到抱歉:
package edu.xsi.webserver;
import java.io.IOException;
import java.net.ServerSocket;
public class WebServer {
int port;
ServerSocket server;
public WebServer(int port) throws IOException{
this.port = port;
this.server = new ServerSocket(port);
Thread t = new Thread(new ServerExec());
t.start();
}
public class ServerExec implements Runnable {
public void run(){
int i = 0;
while (true) {
try {
new WebSession(server.accept(), i++);
System.out.println("Should print before session");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
WebServer webServer = new WebServer(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是处理响应的会话类。
package edu.xsi.webserver;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class WebSession implements Runnable {
Socket client;
int num;
public WebSession(Socket client, int num) {
this.num = num;
this.client = client;
Thread t = new Thread(this);
t.start();
}
public void run() {
Scanner s = null;
DataOutputStream out = null;
try {
s = new Scanner(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
//Get all input from header
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("<html><head></head><body><h1>Hello</h1></body></html>");
s.close();
out.flush();
out.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}