- 浏览: 459624 次
- 性别:
- 来自: 陕西.西安
文章分类
最新评论
-
gaodadawei:
登录失败,请重试楼主,我目前遇到这样一个错误,claros i ...
James+Claros+intouch2.1配置 -
VerRan:
qq346448412 写道请问。你上一节、 用的ORACLE ...
James+Claros+intouch2.1配置 -
qq346448412:
请问。你上一节、 用的ORACLE数据库、 这一节又用的是MY ...
James+Claros+intouch2.1配置 -
paladin1988:
good,我喜欢..
Hibernate自关联关系 -
lygxy12:
请问,能给163发邮件吗?该怎么配置?我安装上面的操作,发给1 ...
James+Claros+intouch2.1配置
1. 服务器类
建立ServerSoke,作为request和response的中枢
2. 处理请求的类
3. 处理响应的类
4. 输出结果
访问地址:http://localhost:8080/index.html
5. 总结
这样我们就实现了一个简单的服务器,不过这里智能处理静态页面,动态页面的处理待续。。。。
建立ServerSoke,作为request和response的中枢
- package ex01.pyrmont;
- import java.net.Socket;
- import java.net.ServerSocket;
- import java.net.InetAddress;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.IOException;
- import java.io.File;
- public class HttpServer {
- /** WEB_ROOT is the directory where our HTML and other files reside.
- * For this package, WEB_ROOT is the "webroot" directory under the working
- * directory.
- * The working directory is the location in the file system
- * from where the java command was invoked.
- */
- public static final String WEB_ROOT =
- System.getProperty("user.dir") + File.separator + "webroot";
- // shutdown command
- private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
- // the shutdown command received
- private boolean shutdown = false;
- public static void main(String[] args) {
- HttpServer server = new HttpServer();
- server.await();
- }
- public void await() {
- ServerSocket serverSocket = null;
- int port = 8080;
- try {
- serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
- }
- catch (IOException e) {
- e.printStackTrace();
- System.exit(1);
- }
- // Loop waiting for a request
- while (!shutdown) {
- Socket socket = null;
- InputStream input = null;
- OutputStream output = null;
- try {
- socket = serverSocket.accept();
- input = socket.getInputStream();
- output = socket.getOutputStream();
- // create Request object and parse
- Request request = new Request(input);
- request.parse();
- // create Response object
- Response response = new Response(output);
- response.setRequest(request);
- response.sendStaticResource();
- // Close the socket
- socket.close();
- //check if the previous URI is a shutdown command
- shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
- }
- catch (Exception e) {
- e.printStackTrace();
- continue;
- }
- }
- }
- }
2. 处理请求的类
- package ex01.pyrmont;
- import java.io.InputStream;
- import java.io.IOException;
- public class Request {
- private InputStream input;
- private String uri;
- public Request(InputStream input) {
- this.input = input;
- }
- public void parse() {
- // Read a set of characters from the socket
- StringBuffer request = new StringBuffer(2048);
- int i;
- byte[] buffer = new byte[2048];
- try {
- i = input.read(buffer);//把输入流中的信息读入字节数组中....
- }
- catch (IOException e) {
- e.printStackTrace();
- i = -1;
- }
- for (int j=0; j<i; j++) {
- request.append((char) buffer[j]);
- }
- 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;
- }
- }
3. 处理响应的类
- package ex01.pyrmont;
- import java.io.OutputStream;
- import java.io.IOException;
- import java.io.FileInputStream;
- import java.io.File;
- /*
- HTTP Response = Status-Line
- *(( general-header | response-header | entity-header ) CRLF)
- CRLF
- [ message-body ]
- Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
- */
- public class Response {
- private static final int BUFFER_SIZE = 1024;
- Request request;
- 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(HttpServer.WEB_ROOT, request.getUri());
- //System.out.print("+++++++++++++++"+request.getUri());
- String tt=request.getUri();
- byte[] xx=new byte[30];
- xx=tt.getBytes();
- output.write(xx,0,xx.length);
- 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 Foundererewrwerwer</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();
- }
- }
- }
4. 输出结果
访问地址:http://localhost:8080/index.html
- GET /index.html HTTP/1.1
- Accept: */*
- Accept-Language: zh-cn
- UA-CPU: x86
- Accept-Encoding: gzip, deflate
- User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler ; .NET CLR 2.0.50727)
- Host: localhost:8080
- Connection: Keep-Alive
5. 总结
这样我们就实现了一个简单的服务器,不过这里智能处理静态页面,动态页面的处理待续。。。。
发表评论
-
springboot学习 - hello world
2017-03-15 18:15 494引子: 开始之前允许我介绍下我认识的spr ... -
Ext显示乱码问题
2012-04-03 13:27 1150转自:http://blog.csdn.net/raren/a ... -
Hadoop学习资料
2011-10-21 10:20 845http://www.cnblogs.com/wayne101 ... -
NodeJs和 mongodb初识
2011-10-20 14:41 1051NodeJS: 提供javascirpt 实现服务器端功能的引 ... -
WebService 非阻塞模式
2011-03-30 16:05 1681package com.datastruct.sort; ... -
利用 Java dump 进行 JVM 故障诊断
2011-01-11 15:58 1449转自:http://jimmyleeee.blog.163.c ... -
LocalTransactionContainment 期间回滚了一个或多个本地事务资源。
2011-01-09 10:29 1964此问题查过很多,但是大家解决方法不一。下面列出 YuLiMin ... -
RETE 算法的描述(转)
2010-07-20 16:57 1280转自:http://www.cnblogs.com/ipoin ... -
Hermes配置
2010-02-02 18:09 1125一直报错UnmarshalException 后来发现 ... -
界面原型设计工具–Balsamiq Mockups
2009-12-09 13:31 1764原文地址:http://www.pbdigg.net/s ... -
JTA 事务使用
2009-11-23 15:20 1555业务场景: 客户下发订单后,订单到竣工需要走三个岗位1,2, ... -
webSphere 下消息驱动Bean 与队列JNDI的关联
2009-09-21 17:44 14611. 消息驱动Bean配置ejb-jar.xml ... -
Hibernate 二级缓存
2008-07-15 10:17 3263Hibernate二级缓存 1. HIbernate.cfg ... -
webService-小记
2008-03-24 18:57 1036A web service has one or more p ... -
Hessian
2008-02-16 11:16 1519Hessian is a simple binary pro ... -
利用反射机制动态将XML信息设置入对象
2007-12-05 14:23 2279引言:XML和J2EE密切的程度是不用说的了,由于我们的接口程 ... -
Action – JSP – Javascript之间的参数传递
2007-11-19 19:04 3633Action – JSP – Javascript之间的参数传 ... -
java 获取存储过程 输出参数
2007-11-13 15:21 5235connection = session.c ... -
js获得<table>的单元格信息
2007-11-08 16:41 54471. 获取表格中的某个单元格的内容 var tid= ... -
Eclipse快捷键
2007-10-23 10:47 914作用域 功能 快捷键 全 ...
相关推荐
在MATLAB环境中实现轻量级随机数生成器——AKARI-I 随机数生成器在科学计算、模拟仿真、加密算法等多个领域中起着至关重要的作用。AKARI-I是一种轻量级的伪随机数生成器,它旨在提供高效、快速且足够随机的数列,...
A parallel, cpu-based matlab implemention of the Hessian Free (HF) optimization (feed forward networks, recurrent neural networks (RNN), multiplicative recurrente neural networks (MRNN))..zip
C4.5-简单实现只需通过Java实现C4.5 您可以尝试使用cd进入文件夹。 然后java -jar xxx.jar运行相应的程序。 TrainWithoutPrune.jar无需修剪即可构建模型。 TrainWithPrune.jar使用修剪构建模型。...
Implements of Deep Learning RecSystem Model with PyTorch and tf2.x 最近从CV转行做推荐,阅读了许多用深度学习做推荐的paper,有感而发,觉得推荐领域论文的工程性大都很强,很多都是从实际的业务和数据出发,在...
### 探究CRC32算法实现原理:为什么采用表驱动实现? #### 一、CRC算法简介 CRC(Cyclic Redundancy Check)是一种用于检测数据传输错误的校验方法,广泛应用于通信领域以及数据存储系统中。CRC的核心在于通过一个...
### 双数组字典树的有效实现 #### 概述 本文档主要介绍了一种高效的字典树(Trie)结构实现方法——双数组字典树(Double Array Trie)。该实现方式旨在结合矩阵形式的快速访问特性和列表形式的紧凑性,从而在减少...
Unofficial_implemention_of_lanenet_model_for_real__lanenet-lane-detection
How to approach Fit to Standard Analysis - Cloud implemention guilde
"simple EDA implemention"是一个使用C++进行简单EDA实现的项目,可能包含了事件驱动的测试框架"EventTest"。通过理解C++与HDL的交互、EDA流程的关键算法以及事件驱动仿真的原理,我们可以构建出一个有效的电子系统...
《TCP-IP Illustrated, Volume 2, The Implemention》.pdf 《TCP-IP Illustrated, Volume 2, The Implemention》.pdf
With features like push notifications, news feed, and an embedded version of Facebook Messenger (a complete app in its own right) all working together in real-time, the complexity and volume of code ...
-For Selling books onlineMaintaining books selling historyAdding and managing booksUser FriendlyFor Implemention of Generic Servlets in JavaThis is a Mini-project developed using Java Jdbc And Generic...
欢迎使用货币转换器 PWA - it is the Implemention of Currency Convertion API - PWA is created by Simple Javascript Service Worker
A ViewPager implemention base on RecyclerView. Support fling operation like gallary. android.support.v4.view.ViewPager的完美替代品 Features: Base on RecyclerView. Custom fling factor. Custom paging ...
- **pytorch-implemention**:强调是PyTorch实现。 - **Python**:编程语言,PyTorch基于Python。 **五、项目结构与使用** "RCNN-master"可能是一个包含RCNN实现的项目文件夹,通常会包含如下结构: - `models`:...
《基于Python的Yolov5-DeepSort车流量统计与轨迹显示源码解析》 在当前的智能交通系统中,车流量统计与车辆轨迹分析扮演着至关重要的角色,它们为城市规划、交通管理以及安全监控提供了重要数据支持。...
leetcode 答案CodeForBlogLearning 博客笔记中的练习代码和leetCode上的...implemention of dataStruct like `LinkList,Stack,Queue and so on` - the answer for algorithm on the LeetCode - maybe others 博客主页:
modern_compiler_implemention现代编译原理 - C 语言描述 笔记随书附带的代码:构建首先要安装 flex, bison, cmake 等工具sudo apt install -y flex bison
SSM框架是Java Web开发中常用的三大框架Spring、Spring MVC和MyBatis的组合,而slf4j(Simple Logging Facade for Java)则是一种日志抽象层,它允许我们选择不同的日志实现,如Logback或Log4j。Gradle作为现代的...
物联网系列物联网(The Internet of Things)的概念是在1999年提出的,它的定义很简单:就是把所有物品通过无线射频识别等资讯感测设备,并且将其连接起来,实现自动化识别和管理。物联网通过智慧型感测系统、识别技术...