用最简单的方式写出自己的服务器
我们平常用TOMCAT,JBOSS ,weblogic的时候我们经常没有注意他们里面的实现过程,糊里糊涂的就用了。现在我用一个简单的例子来解析web服务器运行的原理
import java.util.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer
{
/**
* @param args
*/
public void start()
{
ServerSocket s=null;
System.out.println("webserver starting up on port 8080");
System.out.println("press ctrl-c to exit");
try
{
s=new ServerSocket(8080);
}catch(Exception e)
{
System.out.println("error");
}
System.out.println("wart for ceonnection");
for(;;)
{
try
{
Socket remote= s.accept();
BufferedReader in=new BufferedReader(new InputStreamReader(remote.getInputStream()));
PrintWriter out=new PrintWriter(remote.getOutputStream());
String str=".";
while(!str.equals(""))
{
str=in.readLine();
}
out.println("http/1.0 200 ok");
out.println("content-type:text/html");
out.println("");
out.println("<H1> welcome to the ultra mini-webserver</H1>");
out.flush();
remote.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
WebServer ws=new WebServer();
ws.start();
}
}
只要我们一运行该程序,然后再浏览器上输入http://127.0.0.1:8080就是运行我们的服务器,本例子会显示
welcome to the ultra mini-webserver这个一级标题或许我们可以从这个例子中得到少许启发。
如果对本文章有问题的话,或者你觉得有用的话,下午能回个贴,只求有个鼓励,然后能养成写BLOG的习惯,谢谢大家了哦。
推荐文章 |
