亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

帶線程池的小服務器-Java實現

系統 2053 0

前兩天,利用線程池技術(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編寫的,其實現的復雜程度的確讓人難以想象。

帶線程池的小服務器-Java實現


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

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

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 手机在线观看亚洲国产精品 | 国产精品手机在线观看 | 免费看特级毛片 | 日本美女久久 | 国产在线麻豆一区二区 | 四虎影视国产精品 | 麻豆va一区二区三区久久浪 | 99精品视频不卡在线观看免费 | 国产亚洲欧美一区二区 | 天天干视频在线 | 国产成+人+综合+亚洲 欧美 | 久久综合九色综合国产 | 国产成人精品午夜免费 | 日韩一区二区三区不卡视频 | 日韩女人毛片在线播放 | 一级做性色a爱片久久片 | 麻豆精品永久免费视频 | 国产视频欧美 | 人人爽影院 | 五月情婷婷 | 天天干天天舔天天操 | 成年免费网站 | 777奇米视频| 久久精品国产无限资源 | 亚洲日本高清影院毛片 | 成人影院在线观看视频 | 狠狠色噜噜狠狠狠狠奇米777 | 亚洲精品久久精品h成人 | 国产欧美亚洲精品第二区首页 | 国产福利一区二区精品视频 | 亚洲成a v人片在线观看 | 国产精品麻豆视频 | 亚洲美女在线播放 | 色综合欧美色综合七久久 | 天天干夜夜艹 | 99久久www免费人成精品 | 日韩午夜免费视频 | 亚洲欧美一区二区久久香蕉 | 久久精品美女久久 | 国产精品毛片va一区二区三区 | 97福利视频在线观看 |