您的位置:首页 > 编程语言 > Java开发

基于Java的最简单的Web服务器

2014-01-02 23:52 337 查看
近日学习Java的网络编程,看到一个及其简单的例子,但是却实现了一次Web访问的功能,当然,于Tomcat和Weblogic等Web服务器自然是没法比,可是展现了最基本的Web访问的网络原理的实现,短小精悍,看了才知道,原来还可以这样。

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class HTTPThread implements Runnable {

private Socket socket;
private int count;
public HTTPThread(){

}

public HTTPThread(Socket socket, int count){
this.socket = socket;
this.count = count;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("<html>");
pw.println("<head>");
pw.println("<body>");
pw.println("This my page! You are welcome!");
pw.println("</body>");
pw.println("</head>");
pw.println("</html>");

pw.flush();
pw.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args){
int count = 1;
try {
ServerSocket ss = new ServerSocket(8080);
Socket s = null;
while((s=ss.accept()) != null){
System.out.println("The visitor:" + count);
HTTPThread httpThread = new HTTPThread(s, count);
Thread thread = new Thread(httpThread);
thread.start();
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
编译运行后,通过浏览器访问http://localhost:8080/就可以了,是不是很神奇呢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: