您的位置:首页 > 理论基础 > 计算机网络

一个简单的HTTP服务器

2016-12-09 16:35 148 查看
java使用socket完成的一个http处理的小服务器

功能未完善,单线程,将就着用吧!

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class MyHttpService {
static ServerSocket serverSocket;
static int port = 8081;

public static void main(String[] args) {
Socket socket = null;
//统计用户数量
int countNum = 0;
try {
//监听port端口
serverSocket = new ServerSocket(port);
System.out.println("启动Http服务,监听端口:"+port);
while(true){
socket=serverSocket.accept();//客户端接入,没有接入是在此阻塞
System.out.println("接收第 " + (++countNum) + " 次请求, 地址为:"+socket.getInetAddress()+":"+socket.getPort());
service(socket);

//              try {
//              每处理一个请求休息10秒
//                  TimeUnit.SECONDS.sleep(10);
//              } catch (InterruptedException e) {
//                  e.printStackTrace();
//              }
//              处理100个请求时关闭服务
//              if(countNum==100) break;
}
} catch (IOException e) {
System.out.println("服务异常突退出!");
e.printStackTrace();
} finally {
System.out.println("关闭socket,退出服务!");
close( socket);
}
System.out.println("关闭Http服务, 共处理服务 " + countNum + " 次");
}

//处理请求服务
private static void service(Socket socket){
//资源文件存放的路径
String basePath = MyHttpService.class.getResource("").getFile().substring(1);

BufferedReader br = null;
BufferedReader reader = null;
PrintWriter out = null;

try {
//将接收到的客户端Socket,以流的方式读入缓存
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String header  = reader.readLine();
System.out.println("请求信息第一行:"+header);
String requestPath = header.split(" ")[1];
String requestType = requestPath.substring(requestPath.lastIndexOf("."), requestPath.length());
//判断设置HTTP响应正文的类型
String contentType = "";
if(requestType.equalsIgnoreCase(".html")){
contentType = "text/html";
}else if(requestType.equalsIgnoreCase(".jpg") || requestType.equalsIgnoreCase(".jpeg")){
contentType="image/jpeg";
}else if(requestType.equalsIgnoreCase(".gif")){
contentType="image/gif";
}else{
contentType="application/octet-stream"; //字节流类型
}

out = new PrintWriter(socket.getOutputStream());
//构建响应头信息
out.println("HTTP/1.1 200 OK");
out.println("Content-type:"+contentType);
out.println("Server: MyHttpService");
out.println("");

String line = null;
//取出资源并读取
String filePath = basePath +"server"+requestPath;
if ( new File(filePath).exists()) {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
while((line = br.readLine()) != null){//读取资源文件并输出,或者直接拼接一个html页面输出到浏览器
out.println(line);
}
out.flush();
close(br);
}else{
out.println("请求的资源不存在!");
out.flush();
}
close (reader, out);
System.out.println("完成服务!!!");
} catch (IOException e) {
System.<
c766
span class="hljs-keyword">out.println("============");
out.println("HTTP/1.1 500");//服务异常,返回500
out.println("");
out.flush();
}
}

//关闭流或socket
private static void close(Closeable... closeables){
if(closeables != null){
for(Closeable closeable : closeables){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


用ab进行压力测试,看看表现还行吧,对于

D:\apache\ab>.\ab -n10000 -c100 http://127.0.0.1:8081/index.html This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ 
Benchmarking 127.0.0.1 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests

Server Software:        MyHttpService
Server Hostname:        127.0.0.1
Server Port:            8081

Document Path:          /index.html
Document Length:        149 bytes

Concurrency Level:      100
Time taken for tests:   18.919 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      2150000 bytes
HTML transferred:       1490000 bytes
Requests per second:    528.57 [#/sec] (mean)
Time per request:       189.190 [ms] (mean)
Time per request:       1.892 [ms] (mean, across all concurrent requests)
Transfer rate:          110.98 [Kbytes/sec] received

Connection Times (ms)
min  mean[+/-sd] median   max
Connect:        0    0  11.4      0     511
Processing:    20  186 222.0     80    1392
Waiting:        0  129 172.8     60     871
Total:         20  186 222.7     80    1402

Percentage of the requests served within a certain time (ms)
50%     80
66%    100
75%    130
80%    271
90%    590
95%    670
98%    801
99%    891
100%   1402 (longest request)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息