http服务器

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());
		}
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值