前兩天,利用線程池技術(ThreadPool)寫了個web服務器,其性能當然無法和apache iis等相比,但基本的功能都有了,唯一欠缺的是無法解析動態頁面,采用解釋執行(asp模式的)效率太低,如果采用編譯執行,要么自己編寫一個編譯器來編譯整個動態頁面,要么采用預編譯,很復雜
。。。。
現在把代碼拿出來曬一曬!由于只是初步的設計所以沒有考慮到很多設計模式,代碼在優化上很不到位,請各位高手不吝賜教。
MainServer.java 這是主服務文件,也是提供主線程的類,主線程將請求分發給其他業務線程(workerthread)出來
package com.threadpool;
import java.net.ServerSocket;
public class MainServer
{
?
?public static int clientCount = 0;
?
?//ThreadPool threadPool = null;
?int port;
?PoolManager poolm;
?public MainServer(int port)
?{
??poolm=PoolManager.getInstance();
??poolm.creatThreadPool(100, ActionWorker.class);
??this.port = port;
?}
?public void start() throws Exception
?{
??ServerSocket ss = new ServerSocket(port);
??System.out.println("MainServer is starting.....");
??
??while(true)
??{
???clientCount++;
???poolm.doService(ss.accept());
???System.out.println(clientCount+"connections");
??}
?}
?/**
? * @param args
? * @throws Exception
? */
?public static void main(String[] args) throws Exception
?{
??// TODO Auto-generated method stub
??MainServer server = new MainServer(80);
??server.start();
?}
?
}
PoolManager.java 線程池管理器,該類負責管理線程池,如創建新線程,回收線程等等。
package com.threadpool;
import java.net.Socket;
import Pool.ThreadWorker;
public class PoolManager
{
?//singleton pattern
?private static PoolManager instance = null;
?ThreadPool threadPool = null;
?private PoolManager()
?{
??
?}
?
?public synchronized static PoolManager getInstance()
?{
??if(instance == null)
???instance = new PoolManager();
??
??return instance;
?}
?
?//create thread pool
?public void creatThreadPool(int max, Class<ActionWorker> worker)
?{
??
??try
??{
???threadPool = new ThreadPool(max, worker);
???System.out.println("create a threadpool...");
??}
??catch (Exception e)
??{
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
?}
?
?private WorkerThread getWorker() throws Exception
?{??
??? return threadPool.getWorker();??
?}
?
?public void doService(Object o)
?{??
??try
??{
???getWorker().wake((Socket)o);
???System.out.println(Thread.currentThread().getName());
??}
??catch (Exception e)
??{
???// TODO Auto-generated catch block
???e.printStackTrace();
??}??
?}
}
WorkerThread.java 業務線程類,負責處理具體的請求。
package com.threadpool;
import java.net.Socket;
public class WorkerThread extends Thread
{
?
??private IWorker worker;
??private Socket data;
??private ThreadPool pool;
??WorkerThread(String id, IWorker worker, ThreadPool pool)
??{
???super(id);
???this.worker = worker;
???this.pool = pool;
???this.data = null;
??}
??
??public synchronized void wake(Socket data)
??{
???this.data = data;
???System.out.println("wake up..." + Thread.currentThread().getName());
???notify();
??}
??
??public synchronized void run()
??{
???//boolean stop = false;
???System.out.println("run....");
???while(true)
???{
????if(data == null)
????{
?????try
?????{
??????wait();
??????System.out.println(Thread.currentThread().getName()+"wait...");
?????}
?????catch (InterruptedException e)
?????{
??????// TODO Auto-generated catch block
??????e.printStackTrace();
??????continue;
?????}
????}
????
????System.out.println(this.getName()+"are working"+Thread.currentThread().getName());
????worker.run(data);
????data = null;
????if(!pool.pushBack(this))
?????break;
??}
??
?}
}
IWorker.java為業務邏輯接口
package com.threadpool;
public interface IWorker
{
?public void run(Object data);
}
ActionWorker.java真正干活的那個類,稱為業務邏輯類,與j2ee中的javaBean對應。
package com.threadpool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ActionWorker implements IWorker
{
?
?public void run(Object data)
?{
??handleRequest((Socket)data);
??
?}
?
?private void handleRequest(Socket s)
?{
??try
??{
???InputStream is = s.getInputStream();
???OutputStream os = s.getOutputStream();
???Request request = new Request(is);
???request.parse();
//???// create Response object
???Response response = new Response(os);
??? ??response.setRequest(request);
??? ??response.sendStaticResource();
???System.out.println("worker is working..");
???MainServer.clientCount--;
???//執行完畢后關閉socket,釋放線程
???s.close();
??}
??catch(IOException ex)
??{
???ex.printStackTrace();
??}
??
?}
}
Requset.java封裝請求的類,主要用于提取被請求的文件
package com.threadpool;
import java.io.IOException;
import java.io.InputStream;
public class Request
{
?private InputStream input;
?private String uri;
? ?public Request(InputStream input)
? ?{
??? ?this.input = input;
? ?}
? ?//從請求中解析出文件名
?public void parse()
?{
??StringBuffer request = new StringBuffer(2048);
???? int len;
???? byte[] buffer = new byte[2048];
???? try
???? {
?????? len = input.read(buffer);
???? }
???? catch (IOException e)
???? {
?????? e.printStackTrace();
?????? len = -1;
???? }
???? for (int i=0; i<len; i++)
???? {
?????? request.append((char) buffer[i]);
???? }
???? System.out.print(request.toString());
???? uri = parseUri(request.toString());
? ?}
?//截取請求的文件名
? ?private String parseUri(String requestString)
? ?{
???? int index1, index2;
???? index1 = requestString.indexOf(' ');
???? if (index1 != -1)
???? {
?????? index2 = requestString.indexOf(' ', index1 + 1);
?????? if (index2 > index1)
???????? return requestString.substring(index1 + 1, index2);
???? }
???? return null;
? ?}
? ?public String getUri()
? ?{
???? return uri;
? ?}
}
Response.java 封裝相應流的類
package com.threadpool;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Response
{
?private static final int BUFFER_SIZE = 1024;
? ?public Request request;
? ?public OutputStream output;
? ?public Response(OutputStream output)
? ?{
??? ?this.output = output;
? ?}
? ?public void setRequest(Request request)
? ?{
??? ?this.request = request;
? ?}
? ?public void sendStaticResource() throws IOException
? ?{
???? byte[] bytes = new byte[BUFFER_SIZE];
???? FileInputStream fis = null;
???? try
???? {
????? ??File file = new File(System.getProperty("user.dir")+File.separator+"webroot", request.getUri());
????? ??if (file.exists())
????? ??{
??????? ??fis = new FileInputStream(file);
??????? ??int ch = fis.read(bytes, 0, BUFFER_SIZE);
??????? ??while (ch!=-1)
??????? ??{
????????? ???output.write(bytes, 0, ch);
????????? ???ch = fis.read(bytes, 0, BUFFER_SIZE);
??????? ??}
????? ??}
????? ??else
????? ??{
??????? ??// file not found
??????? ??String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
????????? ??"Content-Type: text/html\r\n" +
????????? ??"Content-Length: 23\r\n" +
????????? ??"\r\n" +
????????? ??"<h1>File Not Found</h1>";
??????? ??output.write(errorMessage.getBytes());
????? ??}
??? ?}
??? ?catch (Exception e)
??? ?{
????? ??// thrown if cannot instantiate a File object
????? ??System.out.println(e.toString() );
??? ?}
??? ?finally
??? ?{
????? ??if (fis!=null)
????? ???fis.close();
??? ?}
? ?}
}
在class文件夾下建立 webroot文件夾作為網站的根目錄,把網頁文件放在下面就可以通過 http://localhost/yourfilename 訪問了,簡單的服務器就寫出來了,由于使用了池技術所以其原理更接近于真正的webserver.
?
ps: apache服務器是用純c編寫的,其實現的復雜程度的確讓人難以想象。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
