serversocket实现动态网页

public class web {
public static void main(String args[]){
	try{Service service=new Service();
	
	
	
	ServerSocket server=new ServerSocket(80);
	service.setServerSocket(server);
	service.start();
	
	}
	catch(Exception e){
		System.out.println(7);
	}


	
	
	
	
}}

class Service extends Thread{
	ServerSocket socket;
	Socket ser;
	String path;File file;String context="";
	public void setServerSocket(ServerSocket socket){
		this.socket=socket;
	}
	public   void run(){
		try{
		
		ser=socket.accept();
		Service service=new Service();
		service.setServerSocket(socket);
		service.start();
		
		InputStream in=ser.getInputStream();
		InputStreamReader r=new InputStreamReader(in);
		BufferedReader br=new BufferedReader(r);
		String readLine=br.readLine();
		while(readLine!=null&&!readLine.equals("")){
			if(readLine.startsWith("GET"))
				path=readLine.substring(4,readLine.length()-9);
				
			System.out.println("获取到的数据"+readLine);
			readLine=br.readLine();
		}
			
			OutputStream output=ser.getOutputStream();
			String html="HTTP/1.1 200 ok\n\n";
			output.write(html.getBytes());
			System.out.println(path);
			if(path.endsWith(".do")){
				
				path=path.substring(1,path.length()-3);
				path="test."+path;
				System.out.println("ok"+path);
				Servlet servlet=(Servlet)Class.forName(path).newInstance();//Servlet是自己写的的类
				Response response=new Response();
				response.setOutputStream(output);
			servlet.service( response);
			}
			else{
			path="D:/web_ceshi"+path;
			if(path!=null)
				 file=new File(path);
			
			int t=0;
			
			if(file!=null&&file.exists()){
				
				FileInputStream fileinput=new FileInputStream(file);
				ByteArrayOutputStream bytearray=new ByteArrayOutputStream(); 
				
				while((t=fileinput.read())!=-1){
					bytearray.write(t);
				}
				output.write(bytearray.toString().getBytes());
				fileinput.close();
				
			}
			
			}
		output.close();
		
	in.close();	
		}
		catch(Exception e){
		System.out.println(1);	
		}
	}
}

public class first implements Servlet{

	

	

	
	public void service( Response arg1)  {
		// TODO Auto-generated method stub
		try{
		arg1.getOutputStream().write("ok".getBytes());}
		catch(IOException e){
			System.out.println("error");
		}
		
	}
	
	
}

interface Servlet{
	public void service(Response arg1);
		
	
}

class Response{
	OutputStream output;
	public void setOutputStream(OutputStream output){
		this.output=output;
	}
	public OutputStream getOutputStream(){
		return output;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值