我一直在努力编写一个简单的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();
}
}
}