paulwong

#

JDK1.5中的线程池ThreadPoolExecutor和JMS的区别

相同点:
都是使用到QUEUE。


不同点:
JMS的QUEUE中放的是数据,也即是当数据来的时候还要去调用其他代码去执行
ThreadPoolExecutor的QUEUE中放的是TASK,也即是有数据和可执行的代码,直接被线程池执行了。

书籍:
http://prefiles.com/hexwk242mjt2/Addison.Wesley.Java.Concurrency.in.Practice.May.2006.rar

posted @ 2013-03-17 12:53 paulwong 阅读(434) | 评论 (0)编辑 收藏

JeeSite 企业信息管理系统基础框架

使用技术
1、Services相关

Core Framework:Spring Framework 3.2。
Security Framework:Apache Shiro 1.2。


2、Web相关

MVC Framework:SpringMVC 3.2。
Layout Decoration:SiteMesh 2.4。
JavaScript Library:JQuery 1.9。
CSS Framework:Twitter Bootstrap 2.0.4。
JavaScript/CSS Compressor:YUI Compressor 2.4。
Front Validation:JQuery Validation Plugin 1.11。


3、Database相关

ORM Framework:Spring-Data-JPA 1.3、Hibernate 4.1。
Connection Pool:BoneCP 0.7
Bean Validation:Hibernate Validation 4.3.0。
Cache:Ehcache 2.6。


4、Tools 相关

Commons:Apache Commons
JSON Mapper:Jackson 2.1
Bean Mapper:Dozer 5.3.2
Full-text search:Hibernate Search 4.2(Apache Lucene 3.6)、IK Analyzer 2012_u6中文分词
Log Manager:Log4j 1.2


http://thinkgem.github.com/jeesite/

https://github.com/thinkgem/jeesite

posted @ 2013-03-17 12:29 paulwong 阅读(2020) | 评论 (0)编辑 收藏

hadoop集群中添加节点步骤

在新节点安装好hadoop


把namenode的有关配置文件复制到该节点


修改masters和slaves文件,增加该节点


设置ssh免密码进出该节点


单独启动该节点上的datanode和tasktracker(hadoop-daemon.sh start datanode/tasktracker)


运行start-balancer.sh进行数据负载均衡


负载均衡:作用:当节点出现故障,或新增加节点时,数据块分布可能不均匀,负载均衡可以重新平衡各个datanode上数据块的分布

posted @ 2013-03-16 23:04 paulwong 阅读(435) | 评论 (0)编辑 收藏

端口扫描程序

If you need 200ms for each of the 65536 ports (in the worst case, a firewall is blocking everything, thus making you hit your timeout for every single port), the maths is pretty simple: you need 13k seconds, or about 3 hours and a half.

You have 2 (non-exclusive) options to make it faster:
  • reduce your timeout
  • paralellize your code
Since the operation is I/O bound (in contrast to CPU bound -- that is, you spend time waiting for I/O, and not for some huge calculation to complete), you can use many, many threads. Try starting with 20. They would divide the 3 hours and a half among them, so the maximum expected time is about 10 minutes. Just remember that this will put pressure on the other side, ie, the scanned host will see huge network activity with "unreasonable" or "strange" patterns, making the scan extremely easy to detect.

The easiest way (ie, with minimal changes) is to use the ExecutorService and Future APIs: @import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

public static Future<Boolean> portIsOpen(final ExecutorService es, final String ip, final int port, final int timeout) {
  return es.submit(new Callable<Boolean>() {
      @Override public Boolean call() {
        try {
          Socket socket = new Socket();
          socket.connect(new InetSocketAddress(ip, port), timeout);
          socket.close();
          return true;
        } catch (Exception ex) {
          return false;
        }
      }
   });
}


Then, you can do something like:

public static void main(final String args) {
  final ExecutorService es = Executors.newFixedThreadPool(20);
  final String ip = "127.0.0.1";
  final int timeout = 200;
  final List<Future<Boolean>> futures = new ArrayList<>();
  for (int port = 1; port <= 65535; port++) {
    futures.add(portIsOpen(es, ip, port, timeout));
  }
  es.shutdown();
  int openPorts = 0;
  for (final Future<Boolean> f : futures) {
    if (f.get()) {
      openPorts++;
    }
  }
  System.out.println("There are " + openPorts + " open ports on host " + ip + " (probed with a timeout of " + timeout + "ms)");
}


If you need to know which ports are open (and not just how many, as in the above example), you'd need to change the return type of the function to Future<SomethingElse>, where SomethingElse would hold the port and the result of the scan, something like:

public final class ScanResult {
  private final int port;
  private final boolean isOpen;
  // constructor
  
// getters
}


Then, change Boolean to ScanResult in the first snippet, and return new ScanResult(port, true) or new ScanResult(port, false) instead of just true or false





posted @ 2013-03-14 10:10 paulwong 阅读(392) | 评论 (0)编辑 收藏

Project management

 

Exercise 1  Web site Development

Using Microsoft Project  2007 (can be downloaded from internet)

A nonprofit organization would like to lead a website development project. The organization has internet access that includes space on a web server, but no experience in developing websites. In addition to creating its website, the organization would like you to train two people on its staff to do simple web page updates. The website should include the following information, as a minimum: description of the organization (mission, history, and recent events), list of services, and contact information. the organization wants the website to include graphics( photographs and other images) and have an attractive, easy way to use layout.

 

1- Project Scope Management: create a WBS for this project and enter the tasks in project 2007. Create milestones and summary tasks. Assume that some of the project management tasks are similar to tasks from the project tracking database project. some of the specific anaylsis, design, and implementation tasks will do:

a) collect information on the organization in hardcopy and digital form( brochures, reports, organization charts)

b) research web site of similar organization

c) collect detailed information about customer's design preferences

d) develop a template for the customer to review (background color of pages, layout of text)

e) create a site map or hierarchy chart showing the flow of website

2- Project Time Management:

a) enter realistic duration for each task, and then link the tasks

b) do Gantt Chart view and Network Diagram View  for the project

c) do schedule table to see key dates and slack times for each task.

 

 

 

 

3- Project Cost Management

a) assume you have three people working on project and each of them would charge $20 per hour. Enter this information in the Resource Sheet.

b) estimate that each person will spend an average of about five hours per week for the four month period. Assign resources to the tasks, and try to make the final cost in line with this estimate

c) do a budget report for your project

4- Project Human Resource Management

a) assume that one project team member will be unavailable due to vacation for two weeks in the middle of the project. Make adjustments to accommodate this vacation so that the schedule does not slip and the costs do not change. Document the changes from the original plan and the new plan.

b) use the Resource Usage view to see each person's work each month. Print a copy of the Resource Usage view.

5- Project Communications Management

a) do a Gantt chart for this project. use a time scale that enables that chart to fit on one page. and the copy and paste it to PowerPoint

b) do a TO DO LIST report for each team member

c) Create a WHO DOES WHAT REPORT

 

 

** Write a two page single spaced paper summarizing what do you think about Microsoft Project. What do you like and What do you dislike about it. Do you think it would be useful for managing all project or just some and which ones.

 

 

posted @ 2013-03-10 18:16 paulwong 阅读(415) | 评论 (0)编辑 收藏

Httpclient资源

http://www.cnblogs.com/wasp520/archive/2012/06/28/2568897.html


http://rensanning.iteye.com/blog/1550436


http://blog.csdn.net/madding/article/details/7638807


抓来的内容当然要提取了:

http://www.oschina.net/p/jsoup

http://www.oschina.net/p/htmlparser

http://www.open-open.com/jsoup/

posted @ 2013-03-01 18:11 paulwong 阅读(516) | 评论 (0)编辑 收藏

职场上千万不做这10件事!那样只会显得你心理幼稚!(转)

标志一、只会踏踏实实地做具体的工作

踏踏实实地做具体工作,这没有错。但只会这样那错就大了,因为这永远只是新手的方式,仅靠这个,永远也成不了高手。甘心一辈子本本分分只当个菜鸟,到头来,肯定连菜鸟也做不成,现在的职场,逆水行舟,原地不动,早晚被浪打翻。

标志二、不会踏踏实实地工作

年轻人喜欢幻想,本身也没错。但若是一天到晚光幻想,那就麻烦了。脱离了现实,好高骛远,白日做梦,眼高手低……漫步云端的感觉是不错,但梦醒时分,从云上跌落粉身碎骨的时候,就追悔莫及了。

标志三、瞧不起上司

受过高等教育的人都清高,别人不如自己的地方很容易放在眼里,并嗤之以鼻,尤其是对领导。让不如自己的人来领导自己,实在不公平。但是,领导之所以是领导,就有原因,不管合理不合理都存在了。也许他学识不行,也许能力不行,但他赢可能就赢在关系上了,可能就赢在心机上了,好的也好,坏的也罢,都是实实在在存在的现象。

标志四、崇拜上司

相比起刚才的这种行为,对上司盲目崇拜,则更显得幼稚。对上司的话全盘接受,无条件服从,缺乏了起码的分析能力,最终会让你在职场中迷失自我。

标志五、容易被激发、被感动、被忽悠

有些人比较感性,我本人也是这样。对于领导一些比较有煽动性东西,难以抵制,很容易用头脑发热。但无论如何,事后一定要冷静思索思索,站在不同的角度来考虑考虑问题,切莫一时意气用事。

标志六、甘当云梯默默无闻

甘当云梯,默默无闻,这本是一种很高尚的情怀。在如今更是难得。但难得归难得,天不佑此类人,生活不助此类人,时代更是难容此类人。对这种人,只能说,老兄,别那么单纯了。

标志七、习惯忍让

喜欢争斗的人让人厌恶,但现在的职场上,也只是这种人才得势。人善被人欺,习惯忍让,别人会觉得你好欺负,这已经成为现在职场上的一种思维定势了。谁也打不破它。

标志八、锋芒毕露

有人则相反,不忍不让,锋芒毕露。这也不好,这样会树敌太多,而且太容易让人看透,很容易中了别人的招儿。适当的时候露露锋芒,展示一下自己的立场就可以了,大多数的情况,还是应该韬光养晦的。

标志九、排斥关系

近几年来,新兴起一门学问,叫做关系学。这里面学问可大了,大到关系职场中的方方面面。可有人就是排斥它,认为靠自己的打拚就已经足够了。其实,职场不比学术,不是把自己关在实验室里就能出成果的,闭门造车,最终自食苦果。

标志十、知无不言言无不真

对别人什么都说,而且什么话都说真的,这很诚实,但太不成熟了。职场上混,就跟下棋一样,尽可能地对方的心理,而不是尽可能地让别人了解自己的心理。道理很浅显。

posted @ 2013-03-01 10:58 paulwong 阅读(409) | 评论 (0)编辑 收藏

JUnitBenchmark Junit性能测试

如果你希望用 JUnit 来测试一些性能问题,那么 JUnitBenchmark 可以帮到你,主要特性:

  • 记录执行时间
  • 监控垃圾收集
  • 测试热身

package com.paul;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import javolution.text.TextBuilder;
import org.junit.Test;
 
/**
 * Benchmark for String concatenation. Compares StringBUilder (JDK) and
 * TextBuilder (Javolution).
 
*/
public class StringConcatenationBenchmark extends AbstractBenchmark {
 
    public static final long LOOPS_COUNT = 10000000;
 
    @Test
    @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1)
    public void stringBuilderBenchmark()  {
         
        StringBuilder builder = new StringBuilder();
        for (long i = 0; i < LOOPS_COUNT; i++) {
            builder.append('i').append(i);
        }
        System.out.println(builder.toString().length());
    }
     
    @Test
    @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1)
    public void textBuilderBenchmark()  {
         
        TextBuilder builder = new TextBuilder();
        for (long i = 0; i < LOOPS_COUNT; i++) {
            builder.append('i').append(i);
        }
        System.out.println(builder.toString().length());
    }
}


Maven依赖:
<dependency>
        <groupId>javolution</groupId>
        <artifactId>javolution</artifactId>
        <version>5.4.5</version>
</dependency>


结果显示:
78888890
78888890
78888890
78888890
StringConcatenationBenchmark.stringBuilderBenchmark: [measured 3 out of 4 rounds, threads: 1 (sequential)]
 round: 0.57 [+- 0.01], round.gc: 0.00 [+- 0.00], GC.calls: 33, GC.time: 0.02, time.total: 2.60, time.warmup: 0.90, time.bench: 1.70
78888890
78888890
78888890
78888890
StringConcatenationBenchmark.textBuilderBenchmark: [measured 3 out of 4 rounds, threads: 1 (sequential)]
 round: 0.46 [+- 0.03], round.gc: 0.00 [+- 0.00], GC.calls: 14, GC.time: 0.14, time.total: 1.92, time.warmup: 0.55, time.bench: 1.38

posted @ 2013-03-01 10:37 paulwong 阅读(820) | 评论 (0)编辑 收藏

EJB3资源

eclipse + JBoss 5 + EJB3开发指南(1):编写第一个无状态的SessionBean


eclipse + JBoss 5 + EJB3开发指南(2):编写有状态的SessionBean


eclipse + JBoss 5 + EJB3开发指南(3):使用Session Bean的本地接口


eclipse + JBoss 5 + EJB3开发指南(4):Session Bean中的注释方法


eclipse + JBoss 5 + EJB3开发指南(5):使用配置文件发布Session Bean


eclipse + JBoss 5 + EJB3开发指南(6):编写第一个实体Bean程序


eclipse + JBoss 5 + EJB3开发指南(7):实现Entity Bean的一对一(one-to-one)映射


eclipse + JBoss 5 + EJB3开发指南(8):实现Entity Bean的一对多(one-to-many)映射


eclipse + JBoss 5 + EJB3开发指南(9):实现Entity Bean的多对多(many-to-many)映射


eclipse + JBoss 5 + EJB3开发指南(10):通过继承实体Bean,将单个表映射成多个表(单表策略,SINGLE_TABLE)


eclipse + JBoss 5 + EJB3开发指南(11):实体Bean的连接策略(JOINED Strategy)


eclipse + JBoss 5 + EJB3开发指南(12):使用命名查询执行JPQL


eclipse + JBoss 5 + EJB3开发指南(13):在Servlet中访问应用程序管制EntityManager对象


eclipse + JBoss 5 + EJB3开发指南(14):消息驱动Bean


eclipse + JBoss 5 + EJB3开发指南(15):拦截器方法和拦截器类


a
JAVAEE6+MAVEN+GLASSFISH
http://www.hascode.com/2011/09/java-ee-6-development-using-the-maven-embedded-glassfish-plugin/



JAVAEE7+MAVEN+GLASSFISH+JBOSS+TOMEE
https://github.com/javaee-samples/javaee7-samples

OPEN EJB客户端
http://openejb.apache.org/hello-world.html
http://tomee.apache.org/clients.html

OPEN EJB互相引用
http://tomee.apache.org/ejb-refs.html

http://tomee.apache.org/tomee-and-eclipse.html

Deploying in TomEE
http://tomee.apache.org/deploying-in-tomee.html

http://www.javacodegeeks.com/2014/05/stateless-ejbs-pooling-and-lifecycle.html

http://www.javacodegeeks.com/2011/11/jboss-as-7-ejb3-pools-configuration.html

http://www.javacodegeeks.com/2014/07/java-ee-7-with-angular-js-part-1.html

SPRING+EJB3+JBOSS
https://github.com/bpark/spring-ejb3-webapp
https://access.redhat.com/documentation/en-US/JBoss_Web_Framework_Kit/1.2/html/Spring_Developer_Guide/ch07s05s02.html


!!JBOSS系列 -EJB远程调用-客户端的配置
http://www.cnblogs.com/liutengteng130/p/4270832.html

JBOSS中远程调用EJB
https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+server+instance


JBOSS 8的DEMO
https://github.com/wildfly/quickstart

EJB VS Spring/Hessian
http://java.dzone.com/articles/remote-access-your-services


posted @ 2013-02-26 10:46 paulwong 阅读(307) | 评论 (0)编辑 收藏

简单的用 Java Socket 编写的 HTTP 服务器应用,帮助学习HTTP协议

所谓HTTP协议,就是TCP协议+状态信息之类的字符。

资源:http://www.blogjava.net/nokiaguy/category/38517.html

/**
 * SimpleHttpServer.java
 
*/

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

/**
 * 一个简单的用 Java Socket 编写的 HTTP 服务器应用, 演示了请求和应答的协议通信内容以及
 * 给客户端返回 HTML 文本和二进制数据文件(一个图片), 同时展示了 404, 200 等状态码.
 * 首先运行这个程序,然后打开Web浏览器,键入http://localhost,则这个程序能够显示出浏览器发送了那些信息
 * 并且向浏览器返回一个网页和一副图片, 并测试同浏览器对话.
 * 当浏览器看到 HTML 中带有图片地址时, 则会发出第二次连接来请求图片等资源.
 * 这个例子可以帮您理解 Java 的 HTTP 服务器软件是基于 J2SE 的 Socket 等软件编写的概念, 并熟悉
 * HTTP 协议.
 * 相反的用 Telnet 连接到已有的服务器则可以帮忙理解浏览器的运行过程和服务器端的返回内容.
 *
 * <pre>
 *       当用户在Web浏览器地址栏中输入一个带有http://前缀的URL并按下Enter后,或者在Web页面中某个以http://开头的超链接上单击鼠标,HTTP事务处理的第一个阶段--建立连接阶段就开始了.HTTP的默认端口是80.
 *    随着连接的建立,HTTP就进入了客户向服务器发送请求的阶段.客户向服务器发送的请求是一个有特定格式的ASCII消息,其语法规则为:
 * < Method > < URL > < HTTP Version > <\n>
 * { <Header>:<Value> <\n>}*
 * <\n>
 * { Entity Body }
 *    请求消息的顶端是请求行,用于指定方法,URL和HTTP协议的版本,请求行的最后是回车换行.方法有GET,POST,HEAD,PUT,DELETE等.
 * 在请求行之后是若干个报头(Header)行.每个报头行都是由一个报头和一个取值构成的二元对,报头和取值之间以":"分隔;报头行的最后是回车换行.常见的报头有Accept(指定MIME媒体类型),Accept_Charset(响应消息的编码方式),Accept_Encoding(响应消息的字符集),User_Agent(用户的浏览器信息)等.
 *    在请求消息的报头行之后是一个回车换行,表明请求消息的报头部分结束.在这个\n之后是请求消息的消息实体(Entity Body).具体的例子参看httpRequest.txt.
 *     Web服务器在收到客户请求并作出处理之后,要向客户发送应答消息.与请求消息一样,应答消息的语法规则为:
 * < HTTP Version> <Status Code> [<Message>]<\n>
 * { <Header>:<Value> <\n> } *
 * <\n>
 * { Entity Body }
 *    应答消息的第一行为状态行,其中包括了HTTP版本号,状态码和对状态码进行简短解释的消息;状态行的最后是回车换行.状态码由3位数字组成,有5类: 
 * 参看:HTTP应答码及其意义 
 * 
 * 1XX 保留 
 * 2XX 表示成功 
 * 3XX 表示URL已经被移走 
 * 4XX 表示客户错误 
 * 5XX 表示服务器错误 
 * 例如:415,表示不支持改媒体类型;503,表示服务器不能访问.最常见的是200,表示成功.常见的报头有:Last_Modified(最后修改时间),Content_Type(消息内容的MIME类型),Content_Length(内容长度)等.
 *    在报头行之后也是一个回车换行,用以表示应答消息的报头部分的结束,以及应答消息实体的开始.
 *    下面是一个应答消息的例子:
 * HTTP/1.0 200 OK
 * Date: Moday,07-Apr-97 21:13:02 GMT
 * Server:NCSA/1.1
 * MIME_Version:1.0
 * Content_Type:text/html
 * Last_Modified:Thu Dec 5 09:28:01 1996
 * Coentent_Length:3107
 * 
 * <HTML><HEAD><TITLE></HTML>
 * 
 * 在用Java语言实现HTTP服务器时,首先启动一个java.net.ServerSocket在提供服务的端口上监听连接.向客户返回文本时,可以用PrintWriter,但是如果返回二进制数据,则必须使用OutputStream.write(byte[])方法,返回的应答消息字符串可以使用String.getBytes()方法转换为字节数组返回,或者使用PrintStream的print()方法写入文本,用write(byte[])方法写入二进制数据.
 * 
 * </pre>
 * 
@author 刘长炯
 * 
@version 1.0 2007-07-24 Sunday
 
*/
public class SimpleHttpServer implements Runnable {
    /**
     * 
     
*/
    ServerSocket serverSocket;//服务器Socket
    
    /**
     * 服务器监听端口, 默认为 80.
     
*/
    public static int PORT=80;//标准HTTP端口
    
    /**
     * 开始服务器 Socket 线程.
     
*/
    public SimpleHttpServer() {
        try {
            serverSocket=new ServerSocket(PORT);
        } catch(Exception e) {
            System.out.println("无法启动HTTP服务器:"+e.getLocalizedMessage());
        }
        if(serverSocket==null)  System.exit(1);//无法开始服务器
        new Thread(this).start();
        System.out.println("HTTP服务器正在运行,端口:"+PORT);
    }
    
    /**
     * 运行服务器主线程, 监听客户端请求并返回响应.
     
*/
    public void run() {
        while(true) {
            try {
                Socket client=null;//客户Socket
                client=serverSocket.accept();//客户机(这里是 IE 等浏览器)已经连接到当前服务器
                if(client!=null) {
                    System.out.println("连接到服务器的用户:"+client);
                    try {
                        // 第一阶段: 打开输入流
                        BufferedReader in=new BufferedReader(new InputStreamReader(
                                client.getInputStream()));
                        
                        System.out.println("客户端发送的请求信息:\n***************");
                        // 读取第一行, 请求地址
                        String line=in.readLine();
                        System.out.println(line);
                        String resource=line.substring(line.indexOf('/'),line.lastIndexOf('/')-5);
                        //获得请求的资源的地址
                        resource=URLDecoder.decode(resource, "UTF-8");//反编码 URL 地址
                        String method = new StringTokenizer(line).nextElement().toString();// 获取请求方法, GET 或者 POST

                        
// 读取所有浏览器发送过来的请求参数头部信息
                        while( (line = in.readLine()) != null) {
                            System.out.println(line);
                            
                            if(line.equals("")) break;
                        }
                        
                        // 显示 POST 表单提交的内容, 这个内容位于请求的主体部分
                        if("POST".equalsIgnoreCase(method)) {
                            System.out.println(in.readLine());
                        }
                        
                        System.out.println("请求信息结束\n***************");
                        System.out.println("用户请求的资源是:"+resource);
                        System.out.println("请求的类型是: " + method);

                        // GIF 图片就读取一个真实的图片数据并返回给客户端
                        if(resource.endsWith(".gif")) {
                            fileService("images/test.gif", client);
                            closeSocket(client);
                            continue;
                        }
                        
                        // 请求 JPG 格式就报错 404
                        if(resource.endsWith(".jpg")) {
                                                    PrintWriter out=new PrintWriter(client.getOutputStream(),true);
                        out.println("HTTP/1.0 404 Not found");//返回应答消息,并结束应答
                        out.println();// 根据 HTTP 协议, 空行将结束头信息
                        out.close();
                        closeSocket(client);
                        continue;
                        } else {
                            // 用 writer 对客户端 socket 输出一段 HTML 代码
                            PrintWriter out=new PrintWriter(client.getOutputStream(),true);
                            out.println("HTTP/1.0 200 OK");//返回应答消息,并结束应答
                            out.println("Content-Type:text/html;charset=GBK");
                            out.println();// 根据 HTTP 协议, 空行将结束头信息

                            out.println("<h1> Hello Http Server</h1>");
                            out.println("你好, 这是一个 Java HTTP 服务器 demo 应用.<br>");
                            out.println("您请求的路径是: " + resource + "<br>");
                            out.println("这是一个支持虚拟路径的图片:<img src='abc.gif'><br>" +
                                    "<a href='abc.gif'>点击打开abc.gif, 是个服务器虚拟路径的图片文件.</a>");
                            out.println("<br>这是个会反馈 404 错误的的图片:<img src='test.jpg'><br><a href='test.jpg'>点击打开test.jpg</a><br>");
                            out.println("<form method=post action='/'>POST 表单 <input name=username value='用户'> <input name=submit type=submit value=submit></form>");
                            out.close();

                            closeSocket(client);
                        }
                    } catch(Exception e) {
                        System.out.println("HTTP服务器错误:"+e.getLocalizedMessage());
                    }
                }
                //System.out.println(client+"连接到HTTP服务器");//如果加入这一句,服务器响应速度会很慢
            } catch(Exception e) {
                System.out.println("HTTP服务器错误:"+e.getLocalizedMessage());
            }
        }
    }
    
    /**
     * 关闭客户端 socket 并打印一条调试信息.
     * 
@param socket 客户端 socket.
     
*/
    void closeSocket(Socket socket) {
        try {
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
                            System.out.println(socket + "离开了HTTP服务器");        
    }
    
    /**
     * 读取一个文件的内容并返回给浏览器端.
     * 
@param fileName 文件名
     * 
@param socket 客户端 socket.
     
*/
        void fileService(String fileName, Socket socket)
    {
            
        try
        {
            PrintStream out = new PrintStream(socket.getOutputStream(), true);
            File fileToSend = new File(fileName);
            if(fileToSend.exists() && !fileToSend.isDirectory())
            {
                out.println("HTTP/1.0 200 OK");//返回应答消息,并结束应答
                out.println("Content-Type:application/binary");
                out.println("Content-Length:" + fileToSend.length());// 返回内容字节数
                out.println();// 根据 HTTP 协议, 空行将结束头信息
                
                FileInputStream fis = new FileInputStream(fileToSend);
                byte data[] = new byte[fis.available()];
                fis.read(data);
                out.write(data);
                out.close();
                fis.close();
            }
        }
        catch(Exception e)
        {
            System.out.println("传送文件时出错:" + e.getLocalizedMessage());
        }
    }
    
    /**
     * 打印用途说明.
     
*/
    private static void usage() {
        System.out.println("Usage: java HTTPServer <port>\nDefault port is 80.");
    }
    
    
    /**
     * 启动简易 HTTP 服务器
     * 
@param args 
     
*/
    public static void main(String[] args) {
        try {
            if(args.length != 1) {
                usage();
            } else if(args.length == 1) {
                PORT = Integer.parseInt(args[0]);
            }
        } catch (Exception ex) {
            System.err.println("Invalid port arguments. It must be a integer that greater than 0");
        }
        
        new SimpleHttpServer();
    }
    

posted @ 2013-02-25 22:29 paulwong 阅读(342) | 评论 (0)编辑 收藏

仅列出标题
共119页: First 上一页 73 74 75 76 77 78 79 80 81 下一页 Last