利用java的Socket编程实现一个小小的web服务器

package com.dqm.tomcat;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class WebTester {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			ServerSocket server = new ServerSocket(8080);
			Socket client = null;
			System.out.println("服务器已经启动,等待客户端连接");
			while(true){
				client = server.accept();
				System.out.println("接受一个请求,访问页面....");
				PrintStream ps = new PrintStream(client.getOutputStream());
				
				BufferedReader br = new BufferedReader(
						new InputStreamReader(
						new FileInputStream("E:\\workspace\\MyJava\\hello.html")));
				String html = "";
				while(html != null){
					html = br.readLine();
					if(html != null){
						ps.println(html);
					}
				}
				ps.close();		
				
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
	}

}

在E:\\workspace\\MyJava\\下面创建hello.html 并且写入以下代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
</head>
<body>
欢迎访问我的web
服务器
</body>
</html>



你可能感兴趣的:(socket编程)