java最简单的web服务器_基于Java的最简单的Web服务器

近日学习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("");

pw.println("

");

pw.println("

");

pw.println("This my page! You are welcome!");

pw.println("");

pw.println("");

pw.println("");

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/就可以了,是不是很神奇呢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值