自己动手写HTTP Server(1)——hello,world篇

自己动手写个类似iis的服务器?

是的,但是功能肯定没有iis强大。

 

 

原理介绍:

1)服务器端监听一个端口;

2)客户端(浏览器)发出请求,比如:输入http://localhost:5555/,回车;

3)服务器端得到请求,返回请求的相应内容,当然了,一定要遵循http协议的格式,要不然那,浏览器是解析不出内容地;

 

学习程序开发的第一步就是hello,world.

今天咱也来个http server开发的hello world,嘿嘿。

 

例子如下:

 

/**
 * @author chen
 * 
 */
public class Myws implements Runnable {

	ServerSocket server;

	/**
	 * @throws IOException
	 * @throws UnknownHostException
	 * 
	 */
	public Myws() throws UnknownHostException, IOException {
		// TODO Auto-generated constructor stub
		server = new ServerSocket(5555);

	}

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Thread t=new Thread(new Myws());
		t.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		boolean listening=true;
		while (listening) {
			try {
				Socket client=server.accept();
				System.out.println("client:"+client);
				PrintStream out = new PrintStream(client.getOutputStream(),
						true);
				String content="<h1>It works.<h1>\r\n";
				out.print("HTTP/1.0 202 OK"+"\r\n");
				out.print("Server: myserver"+"\r\n");
				out.print("Date: "+new Date()+"\r\n");
				out.print("Content-length: "+content.length()+"\r\n");
				out.print("Content-type: text/html"+"\r\n");
				out.print("\r\n");
				out.print(content);
				out.flush();
				out.close();
				client.close();
			} catch (Exception ex) {
				System.out.println(ex.getMessage());
			}
		}
		
		if(server!=null){
			try {
				server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

 

为了突出hello,world的特点,也为了是例子尽量简洁,我是能省就省啊。

 

代码介绍:

 

1)构造函数中初始化ServerSocket,使其监听5555端口:

2)当有客户端请求时(不管请求的内容是什么),统统返回一样的内容,内容是通过out.print(String)实现的;

 

 

好了,运行吧。

 

1)启动main();

2)在浏览器输入localhost:5555,回车:

3)OK,it works.

有图为证:

 

 

虽然可以运行了,但是实在是太蹩脚了。毕竟只是个hello world.

甚至只能对一个客户端相应,下次会对他进行升级,弄个多线程的。

还要分别对get post请求做不同的响应。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值