import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class httpd extends Thread{
public static final int PORT=8380;
protected ServerSocket listen;
public httpd() {
try {
listen=new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
this.start();
}
public static void main(String args[]) {
new httpd();
}
public void run() {
while(true)
{
try {
Socket socket=listen.accept();
Connect connect=new Connect(socket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Connect extends Thread{
Socket client;
BufferedReader isBufferedReader;
DataOutputStream osDataOutputStream;
public Connect(Socket s){
client=s;
try {
isBufferedReader=new BufferedReader(new InputStreamReader(client.getInputStream()));
osDataOutputStream=new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
try {
client.close();
} catch (IOException ex) {
System.out.print("IO error: "+ ex);
}
return;
}
this.start(); //threads start here
}
public void run()
{
try {
String request=isBufferedReader.readLine();
System.out.println("Requset: "+ request);
StringTokenizer stringTokenizer=new StringTokenizer(request);
if (stringTokenizer.countTokens()>=2 && stringTokenizer.nextToken().equals("GET")) {
if ((request=stringTokenizer.nextToken()).startsWith("/")) {
request=request.substring(1);
}
if (request.endsWith("/") ||request.equals(" ")) {
request=request+"index.html";
}
//System.out.println("D://index.html");
File file=new File("D://index.html");
shipDocument(osDataOutputStream,file);
}
else {
osDataOutputStream.writeBytes("400 BAD REQUEST");
}
client.close();
} catch (IOException e) {
System.out.println("IO error"+e);
}
}
public static void shipDocument(DataOutputStream os, File f) throws IOException {
try {
DataInputStream inputStream=new DataInputStream(new FileInputStream(f));
int len=(int)f.length();
byte buf[]=new byte[len];
inputStream.readFully(buf);
os.writeBytes("HTTP/1.0 200 OK \r\n");
os.writeBytes("Content-Length: "+ buf.length +"\r\n");
os.writeBytes("Content-Type: text\\html \r\n");
os.write(buf);
os.flush();
inputStream.close();
} catch (Exception e) {
os.writeBytes(e.toString());
}
}
}
http服务器
最新推荐文章于 2024-10-06 20:16:20 发布