自己动手写个类似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请求做不同的响应。